src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SnowDateTime implements Comparable<SnowDateTime> { public String toQueryFormat() { return "javascript:gs.dateGenerate('" + dateFormat.format(date) + "','00:00:00')"; } SnowDateTime(final Date value); SnowDateTime(final String value); @Deprecated SnowDateTime(final String value, final DateFormat timeFormat); @Override int compareTo(final SnowDateTime another); boolean equals(final SnowDateTime another); Date toDate(); String toDateFormat(); String toDateTimeFormat(); String toTimeFormat(); @Override String toString(); String toQueryFormat(); } | @Test public void toQueryFormat() { String queryFormat = new SnowDateTime(new Date()).toQueryFormat(); assertNotNull(queryFormat); assertTrue(queryFormat.startsWith("javascript:gs.dateGenerate('")); assertTrue(queryFormat.endsWith("')")); assertTrue(queryFormat.contains("','")); assertTrue(queryFormat.contains(":")); assertTrue(queryFormat.contains("-")); } |
SnowDateTime implements Comparable<SnowDateTime> { public String toTimeFormat() { return timeFormat.format(date); } SnowDateTime(final Date value); SnowDateTime(final String value); @Deprecated SnowDateTime(final String value, final DateFormat timeFormat); @Override int compareTo(final SnowDateTime another); boolean equals(final SnowDateTime another); Date toDate(); String toDateFormat(); String toDateTimeFormat(); String toTimeFormat(); @Override String toString(); String toQueryFormat(); } | @Test public void toTimeFormat() { String queryFormat = new SnowDateTime(new Date()).toTimeFormat(); assertNotNull(queryFormat); assertTrue(queryFormat.contains(":")); } |
FilterParser extends StringParser { public static SnowFilter parse(String text) throws StringParseException { FilterParser parser = new FilterParser(text); SnowFilter retval = new SnowFilter(); boolean isAnd = true; String field = null; Predicate predicate = null; String value = null; String token = null; char next = 0; try { while (!parser.eof()) { field = null; predicate = null; value = null; token = null; next = 0; parser.skipWhitespace(); field = parser.readToDelimiter(" !=><"); parser.skipWhitespace(); next = (char) parser.peek(); switch (next) { case '=': predicate = IS; parser.read(); break; case '>': next = (char) parser.readAndPeek(); if ('=' == next) { predicate = GREATER_THAN_EQUALS; parser.read(); } else { predicate = GREATER_THAN; } break; case '<': next = (char) parser.readAndPeek(); if ('=' == next) { predicate = LESS_THAN_EQUALS; parser.read(); } else { predicate = LESS_THAN; } break; case '!': parser.read(); next = (char) parser.peek(); if ('=' == next) { predicate = IS_NOT; parser.read(); break; } else { token = parser.readToken(); if (token.equalsIgnoreCase("empty")) { predicate = IS_NOT_EMPTY; } else if (token.equalsIgnoreCase("like")) { predicate = DOES_NOT_CONTAIN; } else if (token.equalsIgnoreCase("sameas")) { predicate = DIFFERENT_FROM; } else { throw new StringParseException("Negation predicate not recognized at " + parser.getPosition()); } } default: token = parser.readToken(); if ("LIKE".equalsIgnoreCase(token)) { predicate = LIKE; } else if ("IS".equalsIgnoreCase(token)) { predicate = IS; } else if ("CONTAINS".equalsIgnoreCase(token)) { predicate = CONTAINS; } else if ("NSAMEAS".equalsIgnoreCase(token)) { predicate = DIFFERENT_FROM; } else if ("NOT%20LIKE".equalsIgnoreCase(token)) { predicate = DOES_NOT_CONTAIN; } else if ("NOTLIKE".equalsIgnoreCase(token)) { predicate = NOT_LIKE; } else if ("NOT".equalsIgnoreCase(token)) { token = parser.readAndPeekToken(); if ("LIKE".equalsIgnoreCase(token)) { predicate = NOT_LIKE; } else if ("EMPTY".equalsIgnoreCase(token)) { predicate = IS_NOT_EMPTY; } predicate = DOES_NOT_CONTAIN; parser.readToken(); break; } else if ("ENDSWITH".equalsIgnoreCase(token)) { predicate = ENDS_WITH; } else if ("IN".equalsIgnoreCase(token)) { predicate = IN; } else if ("ANYTHING".equalsIgnoreCase(token)) { predicate = IS_ANYTHING; } else if ("ISEMPTY".equalsIgnoreCase(token)) { predicate = IS_EMPTY; } else if ("EMPTYSTRING".equalsIgnoreCase(token)) { predicate = IS_EMPTY_STRING; } else if ("ISNOTEMPTY".equalsIgnoreCase(token)) { predicate = IS_NOT_EMPTY; } else if ("NOTEMPTY".equalsIgnoreCase(token)) { predicate = IS_NOT_EMPTY; } else if ("123TEXTQUERY321".equalsIgnoreCase(token)) { predicate = KEYWORDS; } else if ("SAMEAS".equalsIgnoreCase(token)) { predicate = SAME_AS; } else if ("STARTSWITH".equalsIgnoreCase(token)) { predicate = STARTS_WITH; } break; } if (predicate == null) { throw new StringParseException("Could not determine predicate - last token '" + token + "' at " + parser.getPosition()); } if (predicate.requiresValue()) { value = readValue(parser).trim(); } if (isAnd) { retval.and(field.trim(), predicate, value); } else { retval.or(field.trim(), predicate, value); } parser.skipWhitespace(); if (!parser.eof()) { next = (char) parser.peek(); switch (next) { case '^': next = (char) parser.readAndPeek(); if (' ' == next) { isAnd = true; parser.read(); } token = parser.peek(2); if ("or".equalsIgnoreCase(token)) { isAnd = false; parser.read(); parser.read(); } else { isAnd = true; } break; case '&': next = (char) parser.readAndPeek(); if ('&' == next) { isAnd = true; parser.read(); } else { throw new StringParseException("Invalid AND at " + parser.getPosition()); } break; case '|': next = (char) parser.readAndPeek(); if ('|' == next) { isAnd = false; parser.read(); } else { throw new StringParseException("Invalid OR at " + parser.getPosition()); } break; default: token = parser.readToken(); if ("and".equalsIgnoreCase(token)) { isAnd = true; } if ("or".equalsIgnoreCase(token)) { isAnd = false; parser.readToken(); } else { isAnd = true; } break; } } } } catch (IOException ioe) { StringBuffer b = new StringBuffer(); b.append("IOE: "); b.append(parser.getPosition()); b.append(" field = '"); b.append(field); b.append("' predicate = '"); b.append(predicate); b.append("' value = '"); b.append(value); b.append("' token = '"); b.append(token); b.append("' next = "); b.append(next); throw new StringParseException(b.toString(), ioe); } return retval; } FilterParser(String string); static SnowFilter parse(String text); } | @Test public void testParseDate() { String text = "sys_updated_on>=2015-07-09 00:00:00^sys_updated_on<2015-07-10 00:00:00"; try { SnowFilter filter = FilterParser.parse(text); assertNotNull(filter); assertEquals(filter.clauseCount(), 2); } catch (StringParseException e) { fail("failed to parse '" + text + "' - " + e.getMessage()); } }
@Test public void testParseOR() { String text = "name is REQ123 ^OR number notempty"; try { SnowFilter filter = FilterParser.parse(text); assertNotNull(filter); assertEquals(filter.clauseCount(), 2); } catch (StringParseException e) { fail("failed to parse '" + text + "' - " + e.getMessage()); } }
@Test public void testParseData() { String data = null; try { for (int x = 0; x < testdata.length; x++) { data = testdata[x]; SnowFilter filter = FilterParser.parse(data); assertNotNull( "Should not be null",filter); } } catch (StringParseException e) { System.err.println(data); fail("failed to parse '" + data + "'"); } }
@Test public void testParserComplexFilter() { String text = "install_status != 7 ^ install_status != 8 ^ ci.sys_class_name = u_notebook_pc ^OR ci.sys_class_name = u_tablet_pc ^OR ci.sys_class_name = u_thin_client_pc ^OR ci.sys_class_name = cmdb_ci_desktop_pc ^OR ci.sys_class_name = u_computer_pc ^OR ci.sys_class_name = u_cmdb_virtual_pc ^ ci.u_compensation_code STARTSWITH 8"; try { SnowFilter filter = FilterParser.parse(text); assertNotNull(filter); assertEquals(filter.clauseCount(), 9); System.out.println(filter.toString()); } catch (StringParseException e) { fail("failed to parse '" + text + "' - " + e.getMessage()); } } |
SnowFilter { public SnowFilter() { } SnowFilter(); SnowFilter(final String column, final Predicate predicate, final String value); SnowFilter(final String column, final Predicate predicate); static String encode(final String string); SnowFilter addUpdatedFilter(final SnowDateTime starting, final SnowDateTime ending); SnowFilter and(final SnowClause clause); SnowFilter and(final String column, final Predicate predicate, final String value); SnowFilter and(final String column, final Predicate predicate); boolean isEmpty(); SnowFilter or(final SnowClause clause); SnowFilter or(final String column, final Predicate predicate, final String value); String toEncodedString(); @Override String toString(); int clauseCount(); final static String AND; final static String OR; } | @Test public void snowFilter() { SnowFilter filter = new SnowFilter(); assertNotNull(filter); } |
HmacSha512 extends HeaderDecorator implements RequestDecorator { @Override public void setConfiguration(DataFrame frame) { super.setConfiguration(frame); if (StringUtil.isBlank(getSecret())) { throw new IllegalArgumentException(getClass().getSimpleName() + " decorator must contain a '" + ConfigTag.SECRET + "' configuration element"); } if (StringUtil.isBlank(getData())) { Log.debug(getClass().getSimpleName() + " decorator will only sign messages which contain a body"); } if (StringUtil.isBlank(getHeaderName())) { throw new IllegalArgumentException(getClass().getSimpleName() + " decorator must contain a header name to populate"); } } String getSecret(); void setSecret(String secret); String getData(); void setData(String text); @Override void setConfiguration(DataFrame frame); @Override void process(HttpMessage request); } | @Test public void noHeader() { Config cfg = new Config(); cfg.put(ConfigTag.DATA, "This is a test message"); cfg.put(ConfigTag.SECRET, "ThirtyDirtyBirds"); try { HmacSha512 decorator = new HmacSha512(); decorator.setConfiguration(cfg); fail("Should not allow missing header in configuration"); } catch (Exception e) { } }
@Test public void noSecret() { Config cfg = new Config(); cfg.put(ConfigTag.DATA, "This is a test message"); cfg.put(ConfigTag.HEADER, "Sign"); try { HmacSha512 decorator = new HmacSha512(); decorator.setConfiguration(cfg); fail("Should not allow missing secret in configuration"); } catch (Exception e) { } } |
BasicAuth extends HeaderDecorator implements RequestDecorator { @Override public void process(HttpMessage request) { if (StringUtil.isBlank(getHeaderData())) { calculateHeaderData(); } if (StringUtil.isNotBlank(getHeaderData())) { request.setHeader(getHeaderName(), getHeaderData()); } } BasicAuth(String user, String pswd); BasicAuth(); String getHeaderData(); void setHeaderData(String headerData); String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); @Override void process(HttpMessage request); @Override String getHeaderName(); } | @Test public void test() { String expectedData = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; Config cfg = new Config(); cfg.put(ConfigTag.USERNAME, "Aladdin"); cfg.put(ConfigTag.PASSWORD, "open sesame"); try { BasicAuth decorator = new BasicAuth(); decorator.setConfiguration(cfg); HttpMessage request = getRequest(); decorator.process(request); Header[] headers = request.getHeaders(BasicAuth.DEFAULT_HEADER); assertNotNull(headers); assertTrue(headers.length == 1); Header header = headers[0]; assertNotNull(header); assertEquals(expectedData, header.getValue()); } catch (Exception e) { fail(e.getMessage()); } }
@Test public void specifyHeader() { String headerName = "MyAuth"; String expectedData = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; Config cfg = new Config(); cfg.put(ConfigTag.USERNAME, "Aladdin"); cfg.put(ConfigTag.PASSWORD, "open sesame"); cfg.put(ConfigTag.HEADER, headerName); try { BasicAuth decorator = new BasicAuth(); decorator.setConfiguration(cfg); HttpMessage request = getRequest(); decorator.process(request); Header[] headers = request.getHeaders(headerName); assertNotNull(headers); assertTrue(headers.length == 1); Header header = headers[0]; assertNotNull(header); assertEquals(expectedData, header.getValue()); } catch (Exception e) { fail(e.getMessage()); } }
@Test public void encryptedUsername() { String expectedData = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; Config cfg = new Config(); cfg.put(Loader.ENCRYPT_PREFIX + ConfigTag.USERNAME, "JHhGjEJwi1HQYyJ4SG0gH1ERo0FqHorb"); cfg.put(ConfigTag.PASSWORD, "open sesame"); try { BasicAuth decorator = new BasicAuth(); decorator.setConfiguration(cfg); HttpMessage request = getRequest(); decorator.process(request); Header[] headers = request.getHeaders(BasicAuth.DEFAULT_HEADER); assertNotNull(headers); assertTrue(headers.length == 1); Header header = headers[0]; assertNotNull(header); assertEquals(expectedData, header.getValue()); } catch (Exception e) { fail(e.getMessage()); } }
@Test public void encryptedPassword() { String expectedData = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; Config cfg = new Config(); cfg.put(ConfigTag.USERNAME, "Aladdin"); cfg.put(Loader.ENCRYPT_PREFIX + ConfigTag.PASSWORD, "3nFJqavKpY7Gx+XX8cEgqnQtmzdytnsG3Z+9gKEYaHw="); try { BasicAuth decorator = new BasicAuth(); decorator.setConfiguration(cfg); HttpMessage request = getRequest(); decorator.process(request); Header[] headers = request.getHeaders(BasicAuth.DEFAULT_HEADER); assertNotNull(headers); assertTrue(headers.length == 1); Header header = headers[0]; assertNotNull(header); assertEquals(expectedData, header.getValue()); } catch (Exception e) { fail(e.getMessage()); } }
@Test public void encryptedBoth() { String expectedData = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; Config cfg = new Config(); cfg.put(Loader.ENCRYPT_PREFIX + ConfigTag.USERNAME, "JHhGjEJwi1HQYyJ4SG0gH1ERo0FqHorb"); cfg.put(Loader.ENCRYPT_PREFIX + ConfigTag.PASSWORD, "3nFJqavKpY7Gx+XX8cEgqnQtmzdytnsG3Z+9gKEYaHw="); try { BasicAuth decorator = new BasicAuth(); decorator.setConfiguration(cfg); HttpMessage request = getRequest(); decorator.process(request); Header[] headers = request.getHeaders(BasicAuth.DEFAULT_HEADER); assertNotNull(headers); assertTrue(headers.length == 1); Header header = headers[0]; assertNotNull(header); assertEquals(expectedData, header.getValue()); } catch (Exception e) { fail(e.getMessage()); } } |
Token { public static String unescape(final String text) { if (text == null) { return null; } if (text.indexOf('\\') < 0) { return text; } final int len = text.length(); boolean escaped = false; final StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; ++i) { final char ch = text.charAt(i); if (ch == '\\' && escaped == false) { escaped = true; continue; } escaped = false; builder.append(ch); } return builder.toString(); } static boolean isSeparator(final char ch); static boolean isValid(final String token); static String unescape(final String text); static String unquote(String text); } | @Test public void test005() { unescape(null, null); }
@Test public void test006() { unescape("", ""); }
@Test public void test007() { unescape("abc", "abc"); }
@Test public void test008() { unescape("abc", "ab\\c"); }
@Test public void test009() { unescape("ab\\", "ab\\\\"); }
@Test public void test010() { unescape("ab\\c", "ab\\\\c"); } |
StaticValue extends HeaderDecorator implements RequestDecorator { @Override public void setConfiguration(DataFrame frame) { super.setConfiguration(frame); if (StringUtil.isBlank(getHeaderName())) { throw new IllegalArgumentException(getClass().getSimpleName() + " decorator must contain a header name to populate"); } } StaticValue(); @Override void setConfiguration(DataFrame frame); String getValue(); void setValue(String text); @Override void process(HttpMessage request); } | @Test public void noHeader() { Config cfg = new Config(); cfg.put(ConfigTag.VALUE, "1234-5678-9012-3456"); try { StaticValue decorator = new StaticValue(); decorator.setConfiguration(cfg); fail("Should not allow missing header in configuration"); } catch (Exception e) { } } |
RemoteFile implements Comparable<RemoteFile> { public String getName() { if (filename != null) { int index = filename.lastIndexOf(separatorChar); if (index >= 0) { return filename.substring(index + 1); } else { if (filename == null) { return ""; } else { return filename; } } } else { return ""; } } protected RemoteFile(final String filename, final FileAttributes attrs); String getName(); String getParent(); String getAbsolutePath(); FileAttributes getAttrs(); long getSize(); int getAtime(); int getMtime(); String getModifiedTimeString(); Date getModifiedTime(); @Override String toString(); boolean isDirectory(); boolean isLink(); boolean isAbsolute(); boolean isRelative(); @Override int compareTo(final RemoteFile o); static final char separatorChar; } | @Test public void testGetName() { String test = "data.txt"; RemoteFile subject = new RemoteFile("/home/sdcote/data.txt", null); assertEquals(test, subject.getName()); subject = new RemoteFile("/data.txt", null); assertEquals(test, subject.getName()); subject = new RemoteFile("data.txt", null); assertEquals(test, subject.getName()); } |
RemoteFile implements Comparable<RemoteFile> { public String getParent() { int index = filename.lastIndexOf(separatorChar); if (index > 0) { return filename.substring(0, index); } else { return null; } } protected RemoteFile(final String filename, final FileAttributes attrs); String getName(); String getParent(); String getAbsolutePath(); FileAttributes getAttrs(); long getSize(); int getAtime(); int getMtime(); String getModifiedTimeString(); Date getModifiedTime(); @Override String toString(); boolean isDirectory(); boolean isLink(); boolean isAbsolute(); boolean isRelative(); @Override int compareTo(final RemoteFile o); static final char separatorChar; } | @Test public void testGetParent() { RemoteFile subject = new RemoteFile("/home/sdcote/data.txt", null); assertNotNull(subject.getParent()); assertEquals("/home/sdcote", subject.getParent()); subject = new RemoteFile("/data.txt", null); assertNull(subject.getParent()); subject = new RemoteFile("data.txt", null); assertNull(subject.getParent()); } |
RemoteFile implements Comparable<RemoteFile> { public boolean isRelative() { return !isAbsolute(); } protected RemoteFile(final String filename, final FileAttributes attrs); String getName(); String getParent(); String getAbsolutePath(); FileAttributes getAttrs(); long getSize(); int getAtime(); int getMtime(); String getModifiedTimeString(); Date getModifiedTime(); @Override String toString(); boolean isDirectory(); boolean isLink(); boolean isAbsolute(); boolean isRelative(); @Override int compareTo(final RemoteFile o); static final char separatorChar; } | @Test public void testIsRelative() { RemoteFile subject = new RemoteFile("/home/sdcote/data.txt", null); assertFalse(subject.isRelative()); subject = new RemoteFile("/data.txt", null); assertFalse(subject.isRelative()); subject = new RemoteFile("data.txt", null); assertTrue(subject.isRelative()); subject = new RemoteFile("tmp/data.txt", null); assertTrue(subject.isRelative()); } |
RemoteFile implements Comparable<RemoteFile> { public String getAbsolutePath() { return filename; } protected RemoteFile(final String filename, final FileAttributes attrs); String getName(); String getParent(); String getAbsolutePath(); FileAttributes getAttrs(); long getSize(); int getAtime(); int getMtime(); String getModifiedTimeString(); Date getModifiedTime(); @Override String toString(); boolean isDirectory(); boolean isLink(); boolean isAbsolute(); boolean isRelative(); @Override int compareTo(final RemoteFile o); static final char separatorChar; } | @Test public void testGetAbsolutePath() { RemoteFile subject = new RemoteFile("/home/sdcote/data.txt", null); assertEquals("/home/sdcote/data.txt", subject.getAbsolutePath()); subject = new RemoteFile("/data.txt", null); assertEquals("/data.txt", subject.getAbsolutePath()); subject = new RemoteFile("data.txt", null); assertEquals("data.txt", subject.getAbsolutePath()); subject = new RemoteFile("tmp/data.txt", null); assertEquals("tmp/data.txt", subject.getAbsolutePath()); } |
WildcardFileFilter implements FileFilter { @Override public boolean accept(final RemoteFile file) { return wildcardMatch(file.getName(), getPattern()); } static boolean wildcardMatch(final String filename, final String wildcardMatcher); @Override boolean accept(final RemoteFile file); String getPattern(); void setPattern(final String pattern); } | @Test public void testAccept() {} |
WildcardFileFilter implements FileFilter { public static boolean wildcardMatch(final String filename, final String wildcardMatcher) { if ((filename == null) && (wildcardMatcher == null)) { return true; } if ((filename == null) || (wildcardMatcher == null)) { return false; } final String[] wcs = splitOnTokens(wildcardMatcher); boolean anyChars = false; int textIdx = 0; int wcsIdx = 0; final Stack<int[]> backtrack = new Stack<int[]>(); do { if (backtrack.size() > 0) { final int[] array = backtrack.pop(); wcsIdx = array[0]; textIdx = array[1]; anyChars = true; } while (wcsIdx < wcs.length) { if (wcs[wcsIdx].equals("?")) { textIdx++; if (textIdx > filename.length()) { break; } anyChars = false; } else if (wcs[wcsIdx].equals("*")) { anyChars = true; if (wcsIdx == (wcs.length - 1)) { textIdx = filename.length(); } } else { if (anyChars) { textIdx = checkIndexOf(filename, textIdx, wcs[wcsIdx]); if (textIdx == NOT_FOUND) { break; } final int repeat = checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]); if (repeat >= 0) { backtrack.push(new int[]{wcsIdx, repeat}); } } else { if (!checkRegionMatches(filename, textIdx, wcs[wcsIdx])) { break; } } textIdx += wcs[wcsIdx].length(); anyChars = false; } wcsIdx++; } if ((wcsIdx == wcs.length) && (textIdx == filename.length())) { return true; } } while (backtrack.size() > 0); return false; } static boolean wildcardMatch(final String filename, final String wildcardMatcher); @Override boolean accept(final RemoteFile file); String getPattern(); void setPattern(final String pattern); } | @Test public void testWildcardMatch() {} |
WildcardFileFilter implements FileFilter { protected static boolean checkRegionMatches(final String str, final int strStartIndex, final String search) { return str.regionMatches(IGNORECASE, strStartIndex, search, 0, search.length()); } static boolean wildcardMatch(final String filename, final String wildcardMatcher); @Override boolean accept(final RemoteFile file); String getPattern(); void setPattern(final String pattern); } | @Test public void testCheckRegionMatches() { assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 0, "" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 0, "A" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 0, "AB" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 0, "ABC" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 0, "BC" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 0, "C" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 0, "ABCD" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "", 0, "ABC" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "", 0, "" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 1, "" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 1, "A" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 1, "AB" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 1, "ABC" ) ); assertTrue( WildcardFileFilter.checkRegionMatches( "ABC", 1, "BC" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 1, "C" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "ABC", 1, "ABCD" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "", 1, "ABC" ) ); assertFalse( WildcardFileFilter.checkRegionMatches( "", 1, "" ) ); try { WildcardFileFilter.checkRegionMatches( "ABC", 0, null ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkRegionMatches( null, 0, "ABC" ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkRegionMatches( null, 0, null ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkRegionMatches( "ABC", 1, null ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkRegionMatches( null, 1, "ABC" ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkRegionMatches( null, 1, null ); fail(); } catch ( final NullPointerException ex ) {} } |
WildcardFileFilter implements FileFilter { protected static int checkIndexOf(final String str, final int strStartIndex, final String search) { final int endIndex = str.length() - search.length(); if (endIndex >= strStartIndex) { for (int i = strStartIndex; i <= endIndex; i++) { if (checkRegionMatches(str, i, search)) { return i; } } } return -1; } static boolean wildcardMatch(final String filename, final String wildcardMatcher); @Override boolean accept(final RemoteFile file); String getPattern(); void setPattern(final String pattern); } | @Test public void testCheckIndexOf() { assertEquals( 0, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "A" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 1, "A" ) ); assertEquals( 0, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "AB" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 1, "AB" ) ); assertEquals( 0, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "ABC" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 1, "ABC" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "D" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 3, "D" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 4, "D" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "DE" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 3, "DE" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 4, "DE" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "DEF" ) ); assertEquals( 3, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 3, "DEF" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 4, "DEF" ) ); assertEquals( 9, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "J" ) ); assertEquals( 9, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 8, "J" ) ); assertEquals( 9, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 9, "J" ) ); assertEquals( 8, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "IJ" ) ); assertEquals( 8, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 8, "IJ" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 9, "IJ" ) ); assertEquals( 7, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 6, "HIJ" ) ); assertEquals( 7, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 7, "HIJ" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 8, "HIJ" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "ABCDEFGHIJ", 0, "DED" ) ); assertEquals( -1, WildcardFileFilter.checkIndexOf( "DEF", 0, "ABCDEFGHIJ" ) ); try { WildcardFileFilter.checkIndexOf( "ABC", 0, null ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkIndexOf( null, 0, "ABC" ); fail(); } catch ( final NullPointerException ex ) {} try { WildcardFileFilter.checkIndexOf( null, 0, null ); fail(); } catch ( final NullPointerException ex ) {} assertEquals( 1, WildcardFileFilter.checkIndexOf( "ABC", 0, "BC" ) ); assertEquals( 1, WildcardFileFilter.checkIndexOf( "ABC", 0, "Bc" ) ); assertEquals( 1, WildcardFileFilter.checkIndexOf( "ABC", 0, "BC" ) ); assertEquals( 1, WildcardFileFilter.checkIndexOf( "ABC", 0, "Bc" ) ); } |
WildcardFileFilter implements FileFilter { protected static String[] splitOnTokens(final String text) { if ((text.indexOf('?') == NOT_FOUND) && (text.indexOf('*') == NOT_FOUND)) { return new String[]{text}; } final char[] array = text.toCharArray(); final ArrayList<String> list = new ArrayList<String>(); final StringBuilder buffer = new StringBuilder(); char prevChar = 0; for (final char ch : array) { if ((ch == '?') || (ch == '*')) { if (buffer.length() != 0) { list.add(buffer.toString()); buffer.setLength(0); } if (ch == '?') { list.add("?"); } else if (prevChar != '*') { list.add("*"); } } else { buffer.append(ch); } prevChar = ch; } if (buffer.length() != 0) { list.add(buffer.toString()); } return list.toArray(new String[list.size()]); } static boolean wildcardMatch(final String filename, final String wildcardMatcher); @Override boolean accept(final RemoteFile file); String getPattern(); void setPattern(final String pattern); } | @Test public void testSplitOnTokens() {} |
RemoteSite extends DataFrame { public RemoteSite() { setProtocol(FTP); } RemoteSite(); RemoteSite(URI uri); String getHost(); void setHost(String value); String getPassword(); void setPassword(String value); int getPort(); void setPort(int value); String getProtocol(); void setProtocol(String value); String getProxyHost(); void setProxyHost(String value); int getProxyPort(); void setProxyPort(int value); String getProxyUser(); void setProxyUser(String value); String getUsername(); void setUsername(String value); String getProxyPassword(); void setProxyPassword(String value); static int getProtocolPort(String protocolname); List<RemoteFile> sortMtime(final List<RemoteFile> source); List<RemoteFile> sortAtime(final List<RemoteFile> source); List<RemoteFile> listFiles(final String directory); FileAttributes getAttributes(final String filename); boolean retrieveFile(String remote, String local); boolean publishFile(String local, String remote); void open(); void close(); @Override String toString(); String toFormattedString(); boolean retrieveDirectory(String remote, String local, String pattern, boolean recurse, boolean preserve, boolean delete); static final String PROXY_USER; static final String PROXY_PASSWORD; static final String PROXY_HOST; static final String PROXY_PORT; static final String PROXY_DOMAIN; static String FTP; static String SFTP; static final String HOST_FIELD; static final String PASS_FIELD; static final String PORT_FIELD; static final String PROTOCOL_FIELD; static final String PROXY_HOST_FIELD; static final String PROXY_PORT_FIELD; static final String PROXY_USER_FIELD; static final String USER_FIELD; static final String PROXY_PASS_FIELD; } | @Test public void testRemoteSite() { RemoteSite site = new RemoteSite(); assertNotNull( site ); URI uri; try { uri = new URI( "sftp: site = new RemoteSite( uri ); assertEquals( "username", site.getUsername() ); assertEquals( "password", site.getPassword() ); assertEquals( "host", site.getHost() ); assertEquals( "sftp", site.getProtocol() ); assertTrue( site.getPort() == 23 ); } catch ( URISyntaxException e ) { e.printStackTrace(); } try { uri = new URI( "sftp: site = new RemoteSite( uri ); assertEquals( "username", site.getUsername() ); assertEquals( "password", site.getPassword() ); assertEquals( "host", site.getHost() ); assertEquals( "sftp", site.getProtocol() ); assertTrue( site.getPort() == 22 ); } catch ( URISyntaxException e ) { e.printStackTrace(); } try { uri = new URI( "ftp: site = new RemoteSite( uri ); assertEquals( "username", site.getUsername() ); assertEquals( "password", site.getPassword() ); assertEquals( "host", site.getHost() ); assertEquals( "ftp", site.getProtocol() ); assertTrue( site.getPort() == 21 ); } catch ( URISyntaxException e ) { e.printStackTrace(); } try { uri = new URI( "sftp: site = new RemoteSite( uri ); assertEquals( "username", site.getUsername() ); assertEquals( "password", site.getPassword() ); assertEquals( "host", site.getHost() ); assertEquals( "sftp", site.getProtocol() ); assertTrue( site.getPort() == 33 ); } catch ( URISyntaxException e ) { e.printStackTrace(); } } |
FrameStore { protected static List<FieldSlot> getSlots(DataFrame frame, String parent) { List<FieldSlot> retval = new ArrayList<FieldSlot>(); int seq = 0; for (DataField field : frame.getFields()) { String sysid = GUID.randomSecureGUID().toString(); if (field.isFrame()) { retval.add(new FieldSlot(sysid, parent, seq++, true, field.getName(), field.getType(), null)); retval.addAll(getSlots((DataFrame)field.getObjectValue(), sysid)); } else { retval.add(new FieldSlot(sysid, parent, seq++, true, field.getName(), field.getType(), field.getStringValue())); } } return retval; } private FrameStore(); @SuppressWarnings("unchecked") static String create(DataFrame frame, Connection conn, String entity, String schema, String table, String dialect); static DataFrame read(String sysid, Connection conn, String entity, String schema, String table, String dialect); static boolean update(String sysid, DataFrame frame, Connection conn, String entity, String schema, String table); static boolean delete(String sysid, Connection conn, String entity, String schema, String table); static TableDefinition getTableSchema(String table, String schema); static final String SYSID; static final String ACTIVE; static final String PARENT; static final String SEQUENCE; static final String NAME; static final String VALUE; static final String TYPE; static final String CREATED_BY; static final String CREATED_ON; static final String MODIFIED_BY; static final String MODIFIED_ON; } | @Test public void simpleSlots() { DataFrame frame = new DataFrame().set("Field1", "Value1").set("Field2", "Value2").set("Field3", "Value3"); String parent = "123A"; List<FieldSlot> slots = FrameStore.getSlots(frame, parent); assertTrue(slots.size() == 3); assertTrue(slots.get(2).getName().equals("Field3")); assertTrue(slots.get(1).getName().equals("Field2")); assertTrue(slots.get(0).getName().equals("Field1")); }
@Test public void emptyFrame() { DataFrame frame = new DataFrame(); String parent = "123A"; List<FieldSlot> slots = FrameStore.getSlots(frame, parent); assertNotNull(slots); assertTrue(slots.size() == 0); }
@Test public void treeSlots() { DataFrame frame = new DataFrame().set("Field1", "Value1").set("Field2", new DataFrame().set("Key1", "Value1")).set("Field3", "Value3"); String parent = "123A"; List<FieldSlot> slots = FrameStore.getSlots(frame, parent); assertTrue(slots.size() == 4); assertTrue(slots.get(3).getName().equals("Field3")); assertTrue(slots.get(2).getName().equals("Key1")); assertTrue(slots.get(1).getName().equals("Field2")); assertTrue(slots.get(0).getName().equals("Field1")); assertEquals(slots.get(2).getParent(), slots.get(1).getSysId()); assertTrue(slots.get(3).getSequence() == 2); assertTrue(slots.get(2).getSequence() == 0); assertTrue(slots.get(1).getSequence() == 1); assertTrue(slots.get(0).getSequence() == 0); assertTrue(slots.get(3).getType() == 3); assertTrue(slots.get(2).getType() == 3); assertTrue(slots.get(1).getType() == 0); assertTrue(slots.get(0).getType() == 3); frame = new DataFrame().set("Field1", "Value1").set("Field2", new DataFrame().set("Key1", new DataFrame().set("level", "Three"))).set("Field3", "Value3").set("Field2", new DataFrame().set("Key2", "Value2")); slots = FrameStore.getSlots(frame, parent); assertTrue(slots.size() == 7); } |
DatabaseContext extends PersistentContext { @Override public void close() { final DataFrame frame = new DataFrame(); for (final String key : properties.keySet()) { try { frame.add(key, properties.get(key)); } catch (final Exception e) { Log.debug("Cannot persist property '" + key + "' - " + e.getMessage()); } } frame.put(Symbols.RUN_COUNT, runcount); final Object rundate = get(Symbols.DATETIME); if (rundate != null) { if (rundate instanceof Date) { frame.put(Symbols.PREVIOUS_RUN_DATETIME, rundate); } else { Log.warn(LogMsg.createMsg(CDX.MSG, "Context.run_date_reset", rundate)); } } upsertFields(connection, TABLE_NAME, frame); DatabaseUtil.closeQuietly(connection); super.close(); } @Override void close(); String getIdentity(); @Override void open(); } | @Test public void contextWithLibraryAttribute() { String jobName = "ContextTest"; DataFrame config = new DataFrame() .set("class", "DatabaseContext") .set("target", DB_URL) .set("autocreate", true) .set("library", LIBRARY_LOC) .set("driver", JDBC_DRIVER) .set("username", USER) .set("password", PASS) .set("fields", new DataFrame() .set("SomeKey", "SomeValue") .set("AnotherKey", "AnotherValue") ); TransformEngine engine = new DefaultTransformEngine(); engine.setName(jobName); TransformContext context = new DatabaseContext(); context.setConfiguration(new Config(config)); engine.setContext(context); turnOver(engine); Object obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long runcount = (Long)obj; assertTrue(runcount > 0); turnOver(engine); obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long nextRunCount = (Long)obj; assertEquals(runcount + 1, nextRunCount); context = new DatabaseContext(); context.setConfiguration(new Config(config)); engine.setContext(context); turnOver(engine); obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long lastRunCount = (Long)obj; assertEquals(nextRunCount + 1, lastRunCount); context.close(); } |
DoubleEvaluator extends AbstractEvaluator<Double> { @Override protected Double evaluate(final Constant constant, final Object evaluationContext) { if (PI.equals(constant)) { return Math.PI; } else if (E.equals(constant)) { return Math.E; } else { return super.evaluate(constant, evaluationContext); } } DoubleEvaluator(); DoubleEvaluator(final Parameters parameters); static Parameters getDefaultParameters(); static Parameters getDefaultParameters(final Style style); static final Function ABS; static final Function ACOSINE; static final Function ASINE; static final Function ATAN; static final Function AVERAGE; static final Function CEIL; static final Function COSINE; static final Function COSINEH; static final Operator DIVIDE; static final Constant E; static final Operator EXPONENT; static final Function FLOOR; static final Function LN; static final Function LOG; static final Function MAX; static final Function MIN; static final Operator MINUS; static final Operator MODULO; static final Operator MULTIPLY; static final Operator NEGATE; static final Operator NEGATE_HIGH; static final Constant PI; static final Operator PLUS; static final Function RANDOM; static final Function ROUND; static final Function SINE; static final Function SINEH; static final Function SUM; static final Function TANGENT; static final Function TANGENTH; } | @Test public void testResults() { assertEquals( -2, evaluator.evaluate( "2+-2^2" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "6 / 3" ), 0.001 ); assertEquals( Double.POSITIVE_INFINITY, evaluator.evaluate( "2/0" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "7 % 2.5" ), 0.001 ); assertEquals( -1., evaluator.evaluate( "-1" ), 0.001 ); assertEquals( 1., evaluator.evaluate( "1" ), 0.001 ); assertEquals( -3, evaluator.evaluate( "1+-4" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "3-1" ), 0.001 ); assertEquals( -4, evaluator.evaluate( "-2^2" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "4^0.5" ), 0.001 ); assertEquals( 1, evaluator.evaluate( "sin ( pi /2)" ), 0.001 ); assertEquals( -1, evaluator.evaluate( "cos(pi)" ), 0.001 ); assertEquals( 1, evaluator.evaluate( "tan(pi/4)" ), 0.001 ); assertEquals( Math.PI, evaluator.evaluate( "acos( -1)" ), 0.001 ); assertEquals( Math.PI / 2, evaluator.evaluate( "asin(1)" ), 0.001 ); assertEquals( Math.PI / 4, evaluator.evaluate( "atan(1)" ), 0.001 ); assertEquals( 1, evaluator.evaluate( "ln(e)" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "log(100)" ), 0.001 ); assertEquals( -1, evaluator.evaluate( "min(1,-1)" ), 0.001 ); assertEquals( -1, evaluator.evaluate( "min(8,3,1,-1)" ), 0.001 ); assertEquals( 11, evaluator.evaluate( "sum(8,3,1,-1)" ), 0.001 ); assertEquals( 3, evaluator.evaluate( "avg(8,3,1,0)" ), 0.001 ); assertEquals( 3, evaluator.evaluate( "abs(-3)" ), 0.001 ); assertEquals( 3, evaluator.evaluate( "ceil(2.45)" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "floor(2.45)" ), 0.001 ); assertEquals( 2, evaluator.evaluate( "round(2.45)" ), 0.001 ); double rnd = evaluator.evaluate( "random()" ); assertTrue( rnd >= 0 && rnd <= 1.0 ); assertEquals( evaluator.evaluate( "tanh(5)" ), evaluator.evaluate( "sinh(5)/cosh(5)" ), 0.001 ); assertEquals( -1, evaluator.evaluate( "min(1,min(3+2,2))+-round(4.1)*0.5" ), 0.001 ); }
@Test public void testWithVariable() { String expression = "x+2"; StaticVariableSet<Double> variables = new StaticVariableSet<Double>(); variables.set( "x", 1. ); assertEquals( 3, evaluator.evaluate( expression, variables ), 0.001 ); variables.set( "x", -1. ); assertEquals( 1, evaluator.evaluate( expression, variables ), 0.001 ); }
@Test(expected = IllegalArgumentException.class) public void test2ValuesFollowing() { evaluator.evaluate( "10 5 +" ); }
@Test(expected = IllegalArgumentException.class) public void test2ValuesFollowing2() { evaluator.evaluate( "(10) (5)" ); }
@Test(expected = IllegalArgumentException.class) public void test2OperatorsFollowing() { evaluator.evaluate( "10**5" ); }
@Test(expected = IllegalArgumentException.class) public void testMissingEndValue() { evaluator.evaluate( "10*" ); }
@Test(expected = IllegalArgumentException.class) public void testNoFunctionArgument() { evaluator.evaluate( "sin()" ); }
@Test(expected = IllegalArgumentException.class) public void testEmptyFunctionArgument() { evaluator.evaluate( "min(,2)" ); }
@Test(expected = IllegalArgumentException.class) public void testSomethingBetweenFunctionAndOpenBracket() { evaluator.evaluate( "sin3(45)" ); }
@Test(expected = IllegalArgumentException.class) public void testMissingArgument() { evaluator.evaluate( "min(1,)" ); }
@Test(expected = IllegalArgumentException.class) public void testInvalidArgumentACos() { evaluator.evaluate( "acos(2)" ); }
@Test(expected = IllegalArgumentException.class) public void testInvalidArgumentASin() { evaluator.evaluate( "asin(2)" ); }
@Test(expected = IllegalArgumentException.class) public void testOnlyCloseBracket() { evaluator.evaluate( ")" ); }
@Test(expected = IllegalArgumentException.class) public void testDSuffixInLiteral() { evaluator.evaluate( "3d+4" ); }
@Test(expected = IllegalArgumentException.class) public void testStartWithFunctionSeparator() { evaluator.evaluate( ",3" ); } |
Parameters { public void setTranslation(final Constant constant, final String translatedName) { setTranslation(constant.getName(), translatedName); } Parameters(); void add(final Constant constant); void add(final Function function); void add(final Operator operator); void addConstants(final Collection<Constant> constants); void addExpressionBracket(final BracketPair pair); void addExpressionBrackets(final Collection<BracketPair> brackets); void addFunctionBracket(final BracketPair pair); void addFunctionBrackets(final Collection<BracketPair> brackets); void addFunctions(final Collection<Function> functions); void addMethods(final Collection<Method> methods); void addOperators(final Collection<Operator> operators); String getArgumentSeparator(); Collection<Constant> getConstants(); Collection<BracketPair> getExpressionBrackets(); Collection<BracketPair> getFunctionBrackets(); Collection<Function> getFunctions(); Collection<Method> getMethods(); Collection<Operator> getOperators(); void setFunctionArgumentSeparator(final char separator); void setTranslation(final Constant constant, final String translatedName); void setTranslation(final Function function, final String translatedName); } | @Test public void testMultipleTranslatedName() { Parameters params = DoubleEvaluator.getDefaultParameters(); params.setTranslation( DoubleEvaluator.AVERAGE, "moyenne" ); params.setTranslation( DoubleEvaluator.AVERAGE, "moy" ); DoubleEvaluator evaluator = new DoubleEvaluator( params ); assertEquals( 2, evaluator.evaluate( "moy(3,1)" ), 0.001 ); } |
Parameters { public void setFunctionArgumentSeparator(final char separator) { argumentSeparator = new String(new char[]{separator}); } Parameters(); void add(final Constant constant); void add(final Function function); void add(final Operator operator); void addConstants(final Collection<Constant> constants); void addExpressionBracket(final BracketPair pair); void addExpressionBrackets(final Collection<BracketPair> brackets); void addFunctionBracket(final BracketPair pair); void addFunctionBrackets(final Collection<BracketPair> brackets); void addFunctions(final Collection<Function> functions); void addMethods(final Collection<Method> methods); void addOperators(final Collection<Operator> operators); String getArgumentSeparator(); Collection<Constant> getConstants(); Collection<BracketPair> getExpressionBrackets(); Collection<BracketPair> getFunctionBrackets(); Collection<Function> getFunctions(); Collection<Method> getMethods(); Collection<Operator> getOperators(); void setFunctionArgumentSeparator(final char separator); void setTranslation(final Constant constant, final String translatedName); void setTranslation(final Function function, final String translatedName); } | @Test public void testFunctionArgumentSeparators() { Parameters params = DoubleEvaluator.getDefaultParameters(); params.setFunctionArgumentSeparator( ';' ); DoubleEvaluator evaluator = new DoubleEvaluator( params ); assertEquals( 2, evaluator.evaluate( "avg(3;1)" ), 0.001 ); } |
Decimal implements Comparable<Decimal>, Serializable { public Decimal remainder(final Decimal divisor) { if ((this == NaN) || (divisor == NaN) || divisor.isZero()) { return NaN; } return new Decimal(value.remainder(divisor.value, MATH_CONTEXT)); } private Decimal(); private Decimal(final BigDecimal val); private Decimal(final double val); private Decimal(final int val); private Decimal(final long val); private Decimal(final String val); static Decimal valueOf(final double val); static Decimal valueOf(final int val); static Decimal valueOf(final long val); static Decimal valueOf(final String val); Decimal abs(); @Override int compareTo(final Decimal other); Decimal dividedBy(final Decimal divisor); @Override boolean equals(final Object obj); @Override int hashCode(); boolean isEqual(final Decimal other); boolean isGreaterThan(final Decimal other); boolean isGreaterThanOrEqual(final Decimal other); boolean isLessThan(final Decimal other); boolean isLessThanOrEqual(final Decimal other); boolean isNaN(); boolean isNegative(); boolean isNegativeOrZero(); boolean isPositive(); boolean isPositiveOrZero(); boolean isZero(); Decimal log(); Decimal max(final Decimal other); Decimal min(final Decimal other); Decimal minus(final Decimal subtrahend); Decimal multipliedBy(final Decimal multiplicand); Decimal plus(final Decimal augend); Decimal pow(final int n); Decimal remainder(final Decimal divisor); Decimal sqrt(); double toDouble(); double toDouble(int places); double toDouble(int places, RoundingMode mode); double toTruncatedDouble(int places); @Override String toString(); Decimal getWholePart(); Decimal getFractionalPart(); Decimal getFractionalValue(); Decimal roundUpToWhole(); static final MathContext MATH_CONTEXT; static final Decimal NaN; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; static final Decimal THREE; static final Decimal TEN; static final Decimal HUNDRED; static final Decimal THOUSAND; } | @Test public void testRemainder() { Decimal subject = Decimal.valueOf(5.5D); Decimal result = subject.remainder(Decimal.TWO); Decimal expected = Decimal.valueOf(1.5D); assertTrue(expected.isEqual(result)); } |
Decimal implements Comparable<Decimal>, Serializable { public Decimal getWholePart() { if (this == NaN) { return NaN; } return new Decimal(new BigDecimal(value.toBigInteger())); } private Decimal(); private Decimal(final BigDecimal val); private Decimal(final double val); private Decimal(final int val); private Decimal(final long val); private Decimal(final String val); static Decimal valueOf(final double val); static Decimal valueOf(final int val); static Decimal valueOf(final long val); static Decimal valueOf(final String val); Decimal abs(); @Override int compareTo(final Decimal other); Decimal dividedBy(final Decimal divisor); @Override boolean equals(final Object obj); @Override int hashCode(); boolean isEqual(final Decimal other); boolean isGreaterThan(final Decimal other); boolean isGreaterThanOrEqual(final Decimal other); boolean isLessThan(final Decimal other); boolean isLessThanOrEqual(final Decimal other); boolean isNaN(); boolean isNegative(); boolean isNegativeOrZero(); boolean isPositive(); boolean isPositiveOrZero(); boolean isZero(); Decimal log(); Decimal max(final Decimal other); Decimal min(final Decimal other); Decimal minus(final Decimal subtrahend); Decimal multipliedBy(final Decimal multiplicand); Decimal plus(final Decimal augend); Decimal pow(final int n); Decimal remainder(final Decimal divisor); Decimal sqrt(); double toDouble(); double toDouble(int places); double toDouble(int places, RoundingMode mode); double toTruncatedDouble(int places); @Override String toString(); Decimal getWholePart(); Decimal getFractionalPart(); Decimal getFractionalValue(); Decimal roundUpToWhole(); static final MathContext MATH_CONTEXT; static final Decimal NaN; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; static final Decimal THREE; static final Decimal TEN; static final Decimal HUNDRED; static final Decimal THOUSAND; } | @Test public void testGetWholePart() { Decimal subject = Decimal.valueOf(5.52D); Decimal result = subject.getWholePart(); Decimal expected = Decimal.valueOf(5D); assertTrue(expected.isEqual(result)); } |
Decimal implements Comparable<Decimal>, Serializable { public Decimal getFractionalPart() { if (this == NaN) { return NaN; } return new Decimal(value.remainder(BigDecimal.ONE)); } private Decimal(); private Decimal(final BigDecimal val); private Decimal(final double val); private Decimal(final int val); private Decimal(final long val); private Decimal(final String val); static Decimal valueOf(final double val); static Decimal valueOf(final int val); static Decimal valueOf(final long val); static Decimal valueOf(final String val); Decimal abs(); @Override int compareTo(final Decimal other); Decimal dividedBy(final Decimal divisor); @Override boolean equals(final Object obj); @Override int hashCode(); boolean isEqual(final Decimal other); boolean isGreaterThan(final Decimal other); boolean isGreaterThanOrEqual(final Decimal other); boolean isLessThan(final Decimal other); boolean isLessThanOrEqual(final Decimal other); boolean isNaN(); boolean isNegative(); boolean isNegativeOrZero(); boolean isPositive(); boolean isPositiveOrZero(); boolean isZero(); Decimal log(); Decimal max(final Decimal other); Decimal min(final Decimal other); Decimal minus(final Decimal subtrahend); Decimal multipliedBy(final Decimal multiplicand); Decimal plus(final Decimal augend); Decimal pow(final int n); Decimal remainder(final Decimal divisor); Decimal sqrt(); double toDouble(); double toDouble(int places); double toDouble(int places, RoundingMode mode); double toTruncatedDouble(int places); @Override String toString(); Decimal getWholePart(); Decimal getFractionalPart(); Decimal getFractionalValue(); Decimal roundUpToWhole(); static final MathContext MATH_CONTEXT; static final Decimal NaN; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; static final Decimal THREE; static final Decimal TEN; static final Decimal HUNDRED; static final Decimal THOUSAND; } | @Test public void testGetFractionalPart() { Decimal subject = Decimal.valueOf("5.52"); Decimal result = subject.getFractionalPart(); Decimal expected = Decimal.valueOf("0.52"); assertTrue(expected.isEqual(result)); } |
Decimal implements Comparable<Decimal>, Serializable { public Decimal getFractionalValue() { if (this == NaN) { return NaN; } return new Decimal(value.remainder(BigDecimal.ONE).movePointRight(value.scale()).abs()); } private Decimal(); private Decimal(final BigDecimal val); private Decimal(final double val); private Decimal(final int val); private Decimal(final long val); private Decimal(final String val); static Decimal valueOf(final double val); static Decimal valueOf(final int val); static Decimal valueOf(final long val); static Decimal valueOf(final String val); Decimal abs(); @Override int compareTo(final Decimal other); Decimal dividedBy(final Decimal divisor); @Override boolean equals(final Object obj); @Override int hashCode(); boolean isEqual(final Decimal other); boolean isGreaterThan(final Decimal other); boolean isGreaterThanOrEqual(final Decimal other); boolean isLessThan(final Decimal other); boolean isLessThanOrEqual(final Decimal other); boolean isNaN(); boolean isNegative(); boolean isNegativeOrZero(); boolean isPositive(); boolean isPositiveOrZero(); boolean isZero(); Decimal log(); Decimal max(final Decimal other); Decimal min(final Decimal other); Decimal minus(final Decimal subtrahend); Decimal multipliedBy(final Decimal multiplicand); Decimal plus(final Decimal augend); Decimal pow(final int n); Decimal remainder(final Decimal divisor); Decimal sqrt(); double toDouble(); double toDouble(int places); double toDouble(int places, RoundingMode mode); double toTruncatedDouble(int places); @Override String toString(); Decimal getWholePart(); Decimal getFractionalPart(); Decimal getFractionalValue(); Decimal roundUpToWhole(); static final MathContext MATH_CONTEXT; static final Decimal NaN; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; static final Decimal THREE; static final Decimal TEN; static final Decimal HUNDRED; static final Decimal THOUSAND; } | @Test public void testGetFractionalValue() { Decimal subject = Decimal.valueOf("5.52"); Decimal result = subject.getFractionalValue(); Decimal expected = Decimal.valueOf("52"); assertTrue(expected.isEqual(result)); } |
Decimal implements Comparable<Decimal>, Serializable { public Decimal roundUpToWhole() { BigDecimal retval = new BigDecimal(value.toString()); return new Decimal(retval.setScale(0, RoundingMode.CEILING)); } private Decimal(); private Decimal(final BigDecimal val); private Decimal(final double val); private Decimal(final int val); private Decimal(final long val); private Decimal(final String val); static Decimal valueOf(final double val); static Decimal valueOf(final int val); static Decimal valueOf(final long val); static Decimal valueOf(final String val); Decimal abs(); @Override int compareTo(final Decimal other); Decimal dividedBy(final Decimal divisor); @Override boolean equals(final Object obj); @Override int hashCode(); boolean isEqual(final Decimal other); boolean isGreaterThan(final Decimal other); boolean isGreaterThanOrEqual(final Decimal other); boolean isLessThan(final Decimal other); boolean isLessThanOrEqual(final Decimal other); boolean isNaN(); boolean isNegative(); boolean isNegativeOrZero(); boolean isPositive(); boolean isPositiveOrZero(); boolean isZero(); Decimal log(); Decimal max(final Decimal other); Decimal min(final Decimal other); Decimal minus(final Decimal subtrahend); Decimal multipliedBy(final Decimal multiplicand); Decimal plus(final Decimal augend); Decimal pow(final int n); Decimal remainder(final Decimal divisor); Decimal sqrt(); double toDouble(); double toDouble(int places); double toDouble(int places, RoundingMode mode); double toTruncatedDouble(int places); @Override String toString(); Decimal getWholePart(); Decimal getFractionalPart(); Decimal getFractionalValue(); Decimal roundUpToWhole(); static final MathContext MATH_CONTEXT; static final Decimal NaN; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; static final Decimal THREE; static final Decimal TEN; static final Decimal HUNDRED; static final Decimal THOUSAND; } | @Test public void testRoundUpToWhole() { Decimal subject = Decimal.valueOf("5.52"); Decimal result = subject.roundUpToWhole(); Decimal expected = Decimal.valueOf("6"); assertTrue(expected.isEqual(result)); subject = Decimal.valueOf("5.0"); result = subject.roundUpToWhole(); expected = Decimal.valueOf("5"); assertTrue(expected.isEqual(result)); subject = Decimal.valueOf("-0.5"); result = subject.roundUpToWhole(); expected = Decimal.valueOf("0"); assertTrue(expected.isEqual(result)); subject = Decimal.valueOf("-1.0"); result = subject.roundUpToWhole(); expected = Decimal.valueOf("-1"); assertTrue(expected.isEqual(result)); subject = Decimal.valueOf("-1.9"); result = subject.roundUpToWhole(); expected = Decimal.valueOf("-1"); assertTrue(expected.isEqual(result)); } |
ZipArchive { public void extractTo(final File baseDir) throws IOException { extractTo(baseDir, new AllZipEntryFilter()); } ZipArchive(final File archiveFile); ZipArchive(final URL url); void addEntry(final String entryName, final byte[] data); void addFiles(final File baseDir); void addFiles(final File baseDir, final FilenameFilter filter); void addFiles(final File baseDir, final String archiveBasePath, final FilenameFilter filter); Iterator<String> entryNames(); void extractTo(final File baseDir); void extractTo(final File baseDir, final IZipEntryFilter filter); void extractTo(final File baseDir, final String entryName); void flush(); URL getArchiveURL(); byte[] getEntry(final String entryName); byte[] removeEntry(final String entryName); void setArchiveURL(final URL archiveURL); } | @Test public void testExtractTo() throws Exception { File tstJar = new File( "test.zip" ); ZipArchive archive = new ZipArchive( tstJar ); archive.addFiles( new File( "src" ) ); archive.flush(); File tmpDir = new File( "tmp" ); tmpDir.mkdirs(); ZipArchive arc = new ZipArchive( new File( "test.zip" ) ); arc.extractTo( tmpDir ); FileUtil.removeDir( tmpDir ); FileUtil.deleteFile( tstJar ); } |
SasToken { @Override public String toString() { return buildSasToken(); } SasToken(String scope, String key, long expiry); @Override String toString(); static final String TOKEN_FORMAT; } | @Test public void test() { String scope = "CoyoteIoT.azure-devices.net/devices/george"; long expiry = 1470067491; String key = "6LdAO46ea+1oYydWj2ZSoA=="; String test = "SharedAccessSignature sig=xL98QBjQRcRIX%2FFvT%2F8Orjf3YqIt8rm8boGw%2B9Am%2B6c%3D&se=1470067491&sr=CoyoteIoT.azure-devices.net/devices/george"; SasToken token = new SasToken(scope, key, expiry); assertNotNull(token); String subject = token.toString(); assertNotNull(subject); assertEquals(test, subject); }
@Test public void testBuild() { String hostname = "CoyoteIoT.azure-devices.net"; String deviceId = "george"; String scope = IotHubUri.getResourceUri(hostname, deviceId); long expiry = 1470067491; String key = "6LdAO46ea+1oYydWj2ZSoA=="; String test = "SharedAccessSignature sig=xL98QBjQRcRIX%2FFvT%2F8Orjf3YqIt8rm8boGw%2B9Am%2B6c%3D&se=1470067491&sr=CoyoteIoT.azure-devices.net/devices/george"; SasToken token = new SasToken(scope, key, expiry); assertNotNull(token); String subject = token.toString(); assertNotNull(subject); assertEquals(test, subject); }
@Test public void testBuildOther() { String hostname = "CoyoteIoT.azure-devices.net"; String deviceId = "device-fcbd127a"; String scope = IotHubUri.getResourceUri(hostname, deviceId); long expiry = 1501598806; String key = "ypZ2F76vfOkYYHKsRbQOYP6SKW7/TOo4maD9GmqYMII="; SasToken token = new SasToken(scope, key, expiry); assertNotNull(token); String subject = token.toString(); assertNotNull(subject); System.out.println(subject); } |
Multiply extends AbstractMathTransform implements FrameTransform { @Override public void setConfiguration(Config cfg) throws ConfigurationException { super.setConfiguration(cfg); setSource(getString(ConfigTag.SOURCE)); setFactor(getString(FACTOR)); if (StringUtil.isBlank(getFactor())) { throw new ConfigurationException("Multiply transform requires a multiplication factor"); } } @Override void setConfiguration(Config cfg); @Override DataFrame performTransform(DataFrame frame); void setFactor(String factor); String getSource(); void setSource(String src); static final String FACTOR; } | @Test public void basic() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"factor\" : \"10\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame().set("TotalCost", "7"); context.setSourceFrame(sourceFrame); try (Multiply transformer = new Multiply()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); long value = result.getAsLong("TotalCost"); assertTrue(value == 70); } }
@Test public void source() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"source\" : \"Count\", \"factor\" : \"3.50\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame().set("Count", "6"); context.setSourceFrame(sourceFrame); try (Multiply transformer = new Multiply()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); double value = result.getAsDouble("TotalCost"); assertTrue(value == 21); } }
@Test public void setSymbol() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"source\" : \"Count\", \"factor\" : \"3.50\", \"setsymbol\": true }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); getTransformContext().setSymbols(new SymbolTable()); DataFrame sourceFrame = new DataFrame().set("Count", "3"); context.setSourceFrame(sourceFrame); try (Multiply transformer = new Multiply()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); double value = result.getAsDouble("TotalCost"); assertTrue(value == 10.5); Object symbol = getTransformContext().getSymbols().get("TotalCost"); assertNotNull(symbol); assertTrue(symbol instanceof String); assertTrue("10.5".equals(symbol)); } } |
Guid extends AbstractFieldTransform implements FrameTransform { @Override public void setConfiguration(Config cfg) throws ConfigurationException { super.setConfiguration(cfg); if (cfg.containsIgnoreCase(ConfigTag.SECURE)) { try { secure = cfg.getBoolean(ConfigTag.SECURE); } catch (Throwable ball) { throw new ConfigurationException("Invalid boolean value"); } } } @Override void setConfiguration(Config cfg); } | @Test public void test() throws ConfigurationException, IOException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"Id\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); context.setSourceFrame(sourceFrame); try (Guid transformer = new Guid()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); String value = result.getAsString("Id"); assertTrue(StringUtil.isNotBlank(value)); result = transformer.process(sourceFrame); assertNotNull(result); String nextValue = result.getAsString("Id"); assertTrue(StringUtil.isNotBlank(value)); assertFalse(value.equals(nextValue)); } }
@Test public void secure() throws ConfigurationException, IOException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"Id\", \"secure\" : true }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); context.setSourceFrame(sourceFrame); try (Guid transformer = new Guid()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); String value = result.getAsString("Id"); assertTrue(StringUtil.isNotBlank(value)); result = transformer.process(sourceFrame); assertNotNull(result); String nextValue = result.getAsString("Id"); assertTrue(StringUtil.isNotBlank(value)); assertFalse(value.equals(nextValue)); } } |
Text extends AbstractFieldTransform implements FrameTransform { @Override public DataFrame process(final DataFrame frame) throws TransformException { DataFrame retval = frame; DataField field = retval.getField(getFieldName()); if (field != null) { String format = getConfiguration().getString(ConfigTag.FORMAT); if (StringUtil.isNotBlank(format)) { String text = ""; short type = field.getType(); switch (type) { case DataField.DOUBLE: text = new DecimalFormat(format).format((double)field.getObjectValue()); break; case DataField.FLOAT: text = new DecimalFormat(format).format((float)field.getObjectValue()); break; case DataField.S64: case DataField.U32: text = NumberFormat.getInstance().format((long)field.getObjectValue()); break; case DataField.S32: case DataField.U16: text = NumberFormat.getInstance().format((int)field.getObjectValue()); break; case DataField.S16: case DataField.U8: text = NumberFormat.getInstance().format((short)field.getObjectValue()); break; case DataField.DATE: text = new SimpleDateFormat(format).format((java.util.Date)field.getObjectValue()); break; case DataField.STRING: if (UPPERCASE.equals(format)) { text = field.getStringValue(); if (StringUtil.isNotBlank(text)) { text = text.toUpperCase(); } } else if (LOWERCASE.equals(format)) { text = field.getStringValue(); if (StringUtil.isNotBlank(text)) { text = text.toLowerCase(); } } else { text = guess(field, format); } if (text == null) { Log.error("Data field '" + field.getName() + "' of type 'String' could not be converted into a formattable type - Value: '" + field.getStringValue() + "'"); } break; default: Log.error("Data field '" + field.getName() + "' of type : " + field.getTypeName() + " cannot be formatted"); break; } if (StringUtil.isNotBlank(text)) { retval.put(field.getName(), text); } } else { retval.put(field.getName(), field.getStringValue()); } } return retval; } @Override DataFrame process(final DataFrame frame); } | @Test public void basic() throws IOException, ConfigurationException, TransformException { String cfgData = "{ \"field\" : \"number\", \"format\" : \"#,###\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("number", 123456); context.setSourceFrame(sourceFrame); try (Text transformer = new Text()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject("number"); assertTrue(obj instanceof String); assertEquals("123,456", obj.toString()); } }
@Test public void doubleTest() throws IOException, ConfigurationException, TransformException { String cfgData = "{ \"field\" : \"number\", \"format\" : \"#,###.000\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("number", 123456.05); context.setSourceFrame(sourceFrame); try (Text transformer = new Text()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject("number"); assertTrue(obj instanceof String); assertEquals("123,456.050", obj.toString()); } }
@Test public void formatDate() throws IOException, ConfigurationException, TransformException { String cfgData = "{ \"field\" : \"date\", \"format\" : \"HH:mm:ss\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("date", new java.util.Date()); context.setSourceFrame(sourceFrame); try (Format transformer = new Format()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject("date"); assertTrue(obj instanceof String); assertTrue(obj.toString().length() == 8); } }
@Test public void guessDate() throws IOException, ConfigurationException, TransformException { String FIELDNAME = "date"; DataFrame cfg = new DataFrame().set("field", FIELDNAME).set("format", "HH:mm:ss"); Config configuration = new Config(cfg); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put(FIELDNAME, new java.util.Date().toString()); context.setSourceFrame(sourceFrame); try (Text transformer = new Text()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject(FIELDNAME); assertTrue(obj instanceof String); assertTrue(obj.toString().length() == 8); } }
@Test public void guessDouble() throws IOException, ConfigurationException, TransformException { String FIELDNAME = "number"; DataFrame cfg = new DataFrame().set("field", FIELDNAME).set("format", "#,###.000"); Config configuration = new Config(cfg); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put(FIELDNAME, "12345.05"); context.setSourceFrame(sourceFrame); try (Text transformer = new Text()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject(FIELDNAME); assertTrue(obj instanceof String); assertEquals("12,345.050", obj.toString()); } }
@Test public void guessNumber() throws IOException, ConfigurationException, TransformException { String FIELDNAME = "number"; DataFrame cfg = new DataFrame().set("field", FIELDNAME).set("format", "#,###"); Config configuration = new Config(cfg); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put(FIELDNAME, "1234"); context.setSourceFrame(sourceFrame); try (Text transformer = new Text()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); Object obj = result.getObject(FIELDNAME); assertTrue(obj instanceof String); assertEquals("1,234", obj.toString()); } } |
Date extends AbstractFieldTransform implements FrameTransform { @Override public DataFrame process(final DataFrame frame) throws TransformException { DataFrame retval = frame; DataField field = retval.getField(getFieldName()); if (field != null) { String token = getConfiguration().getString(ConfigTag.FORMAT); if (StringUtil.isNotBlank(token)) { String format = token.toLowerCase().trim(); switch (format) { case NOW: field = setNow(field); break; case SECONDS: case UNIX: field = processSeconds(field); break; case JAVA: case MILLISECONDS: field = processMilliseconds(field); break; default: field = setFormatDate(field, token); break; } } else { field = processField(field); } retval.put(field.getName(), field.getObjectValue()); } return retval; } @Override DataFrame process(final DataFrame frame); } | @Test public void unixTime() throws ConfigurationException, IOException, TransformException, DataFrameException { DataFrame cfg = new DataFrame().set("field", "date").set("format", "seconds"); System.out.println(cfg.toString()); Config configuration = new Config(cfg); DataFrame workingFrame = new DataFrame(); workingFrame.put("date", "1513620300"); try (Date transformer = new Date()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(workingFrame); assertNotNull(result); DataField dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); Object value = dateField.getObjectValue(); assertNotNull(value); assertTrue(value instanceof java.util.Date); java.util.Date date = (java.util.Date)value; System.out.println(date.toString()); } }
@Test public void javaTime() throws ConfigurationException, IOException, TransformException, DataFrameException { DataFrame cfg = new DataFrame().set("field", "date").set("format", "milliseconds"); System.out.println(cfg.toString()); Config configuration = new Config(cfg); DataFrame workingFrame = new DataFrame(); workingFrame.put("date", "1513655245615"); try (Date transformer = new Date()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(workingFrame); assertNotNull(result); DataField dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); Object value = dateField.getObjectValue(); assertNotNull(value); assertTrue(value instanceof java.util.Date); System.out.println(value.toString()); } }
@Test public void now() throws ConfigurationException, IOException, TransformException, DataFrameException { DataFrame cfg = new DataFrame().set("field", "date").set("format", "now"); System.out.println(cfg.toString()); Config configuration = new Config(cfg); DataFrame workingFrame = new DataFrame(); workingFrame.put("date", "SomeValue"); try (Date transformer = new Date()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(workingFrame); assertNotNull(result); DataField dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); Object value = dateField.getObjectValue(); assertNotNull(value); assertTrue(value instanceof java.util.Date); System.out.println(value.toString()); } }
@Test public void invalidFormat() throws ConfigurationException, IOException, DataFrameException { DataFrame cfg = new DataFrame().set("field", "date").set("format", "unixTime"); Config configuration = new Config(cfg); DataFrame workingFrame = new DataFrame(); workingFrame.put("date", "1513620300"); try (Date transformer = new Date()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); transformer.process(workingFrame); fail("Should not support invalid format"); } catch (TransformException e) { } }
@Test public void bestGuess() throws ConfigurationException, IOException, TransformException, DataFrameException { DataFrame cfg = new DataFrame().set("field", "date"); System.out.println(cfg.toString()); Config configuration = new Config(cfg); DataFrame workingFrame = new DataFrame(); try (Date transformer = new Date()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); workingFrame.put("date", "2017-12-19 13:22:14"); DataFrame result = transformer.process(workingFrame); assertNotNull(result); DataField dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); Object value = dateField.getObjectValue(); assertNotNull(value); assertTrue(value instanceof java.util.Date); System.out.println(value.toString()); workingFrame.put("date", "2017-12-19"); result = transformer.process(workingFrame); assertNotNull(result); dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); value = dateField.getObjectValue(); System.out.println(value.toString()); workingFrame.put("date", "12-18-2017 09:03:27"); result = transformer.process(workingFrame); assertNotNull(result); dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); value = dateField.getObjectValue(); System.out.println(value.toString()); workingFrame.put("date", "12-18-2017"); result = transformer.process(workingFrame); assertNotNull(result); dateField = result.getField("date"); assertTrue(dateField.getType() == DataField.DATE); value = dateField.getObjectValue(); } } |
Subtract extends AbstractMathTransform implements FrameTransform { @Override public void setConfiguration(Config cfg) throws ConfigurationException { super.setConfiguration(cfg); setMinuend(getString(MINUEND)); setSubtrahend(getString(SUBTRAHEND)); if (StringUtil.isBlank(getSubtrahend())) { throw new ConfigurationException("Subtract transform requires a subtrahend"); } if (StringUtil.isEmpty(getMinuend())) { setMinuend(getFieldName()); } } @Override void setConfiguration(Config cfg); @SuppressWarnings("unchecked") @Override DataFrame performTransform(DataFrame frame); static final String MINUEND; static final String SUBTRAHEND; } | @Test public void basic() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"subtrahend\" : \"10\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame().set("TotalCost", "7"); context.setSourceFrame(sourceFrame); try (Subtract transformer = new Subtract()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); long value = result.getAsLong("TotalCost"); assertTrue(value == -3); } }
@Test public void source() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"minuend\" : \"Count\", \"subtrahend\" : \"3.50\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame().set("Count", "6"); context.setSourceFrame(sourceFrame); try (Subtract transformer = new Subtract()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); double value = result.getAsDouble("TotalCost"); assertTrue(value == 2.5D); } }
@Test public void setSymbol() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"minuend\" : \"Count\", \"subtrahend\" : \"3.50\", \"setsymbol\": true }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); getTransformContext().setSymbols(new SymbolTable()); DataFrame sourceFrame = new DataFrame().set("Count", "6"); context.setSourceFrame(sourceFrame); try (Subtract transformer = new Subtract()) { transformer.setConfiguration(configuration); transformer.open(getTransformContext()); DataFrame result = transformer.process(sourceFrame); assertNotNull(result); double value = result.getAsDouble("TotalCost"); assertTrue(value == 2.5D); Object symbol = getTransformContext().getSymbols().get("TotalCost"); assertNotNull(symbol); assertTrue(symbol instanceof String); assertTrue("2.5".equals(symbol)); } } |
CheckFieldMethod extends AbstractBooleanMethod { private static Boolean equalTo(final Object fieldObject, final Object expectedObject) { boolean retval = true; if (fieldObject == null && expectedObject == null) { retval = true; } else { if (fieldObject == null || expectedObject == null) { retval = false; } else { if (fieldObject.getClass().equals(expectedObject.getClass())) { retval = fieldObject.equals(expectedObject); } else { return compare(fieldObject, expectedObject) == 0; } } } return retval; } private CheckFieldMethod(); static Boolean execute(final TransformContext context, final String field, final String operator, final String expected); } | @Test public void equalTo() { assertTrue(CheckFieldMethod.execute(transformContext, "name", "EQ", "Bob")); assertTrue(CheckFieldMethod.execute(transformContext, "name", "==", "Bob")); assertTrue(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.EQ.toString(), "Bob")); assertFalse(CheckFieldMethod.execute(transformContext, "name", "EQ", "BoB")); assertFalse(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.EQ.toString(), "BOB")); assertFalse(CheckFieldMethod.execute(transformContext, "name", "EQ", "Robert")); assertFalse(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.EQ.toString(), "Robert")); assertTrue(CheckFieldMethod.execute(transformContext, "Source.IntegerField", "EQ", "123")); assertTrue(CheckFieldMethod.execute(transformContext, "Source.IntegerField", "EQ", "Working.DoubleValue")); } |
CheckFieldMethod extends AbstractBooleanMethod { public static Boolean execute(final TransformContext context, final String field, final String operator, final String expected) throws IllegalArgumentException { if (field == null) { throw new IllegalArgumentException("Null field parameter"); } if (operator == null) { throw new IllegalArgumentException("Null operator parameter"); } if (expected == null) { throw new IllegalArgumentException("Null expected value parameter"); } if (context == null) { throw new IllegalArgumentException("Null transform context parameter"); } String key = sanitize(field); final Object fieldObject = context.resolveToValue(key); key = sanitize(expected); Object expectedObject = context.resolveToValue(key); if (expectedObject == null) { if (NumberUtil.isNumeric(expected)) { expectedObject = NumberUtil.parse(expected); } else { expectedObject = expected; } } try { final Operator oper = Operator.getOperator(operator); switch (oper) { case EQ: return equalTo(fieldObject, expectedObject); case EI: return equalsIgnoreCase(fieldObject, expectedObject); case LT: return lessThan(fieldObject, expectedObject); case LE: return lessThanEquals(fieldObject, expectedObject); case GT: return greaterThan(fieldObject, expectedObject); case GE: return greaterThanEquals(fieldObject, expectedObject); case NE: return notEqual(fieldObject, expectedObject); default: return false; } } catch (Exception e) { Log.notice(CLASS + ": " + e.getMessage()); return false; } } private CheckFieldMethod(); static Boolean execute(final TransformContext context, final String field, final String operator, final String expected); } | @Test public void equalToIgnoreCase() { assertTrue(CheckFieldMethod.execute(transformContext, "name", "EI", "BOB")); assertTrue(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.EI.toString(), "BOB")); assertFalse(CheckFieldMethod.execute(transformContext, "name", "EI", "Robert")); assertFalse(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.EI.toString(), "Robert")); }
@Test public void lessThanEqualTo() { assertTrue(CheckFieldMethod.execute(transformContext, "one", "LE", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "one", "<=", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "one", CheckFieldMethod.Operator.LE.toString(), "2")); assertTrue(CheckFieldMethod.execute(transformContext, "two", "LE", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "two", CheckFieldMethod.Operator.LE.toString(), "2")); }
@Test public void greaterThanEqualTo() { assertTrue(CheckFieldMethod.execute(transformContext, "two", "GE", "1")); assertTrue(CheckFieldMethod.execute(transformContext, "two", ">=", "1")); assertTrue(CheckFieldMethod.execute(transformContext, "two", CheckFieldMethod.Operator.GE.toString(), "1")); assertTrue(CheckFieldMethod.execute(transformContext, "two", "GE", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "two", CheckFieldMethod.Operator.GE.toString(), "2")); assertFalse(CheckFieldMethod.execute(transformContext, "two", "GE", "3")); assertFalse(CheckFieldMethod.execute(transformContext, "two", CheckFieldMethod.Operator.GE.toString(), "3")); } |
CheckFieldMethod extends AbstractBooleanMethod { private static Boolean lessThan(final Object fieldObject, final Object expectedObject) { return compare(fieldObject, expectedObject) < 0; } private CheckFieldMethod(); static Boolean execute(final TransformContext context, final String field, final String operator, final String expected); } | @Test public void lessThan() { assertTrue(CheckFieldMethod.execute(transformContext, "one", "LT", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "one", "<", "2")); assertTrue(CheckFieldMethod.execute(transformContext, "one", CheckFieldMethod.Operator.LT.toString(), "2")); } |
CheckFieldMethod extends AbstractBooleanMethod { private static Boolean greaterThan(final Object fieldObject, final Object expectedObject) { return compare(fieldObject, expectedObject) > 0; } private CheckFieldMethod(); static Boolean execute(final TransformContext context, final String field, final String operator, final String expected); } | @Test public void greaterThan() { assertTrue(CheckFieldMethod.execute(transformContext, "two", "GT", "1")); assertTrue(CheckFieldMethod.execute(transformContext, "two", ">", "1")); assertTrue(CheckFieldMethod.execute(transformContext, "two", CheckFieldMethod.Operator.GT.toString(), "1")); assertFalse(CheckFieldMethod.execute(transformContext, "one", "GT", "1")); assertFalse(CheckFieldMethod.execute(transformContext, "one", CheckFieldMethod.Operator.GT.toString(), "1")); } |
CheckFieldMethod extends AbstractBooleanMethod { private static Boolean notEqual(final Object fieldObject, final Object expectedObject) { return compare(fieldObject, expectedObject) != 0; } private CheckFieldMethod(); static Boolean execute(final TransformContext context, final String field, final String operator, final String expected); } | @Test public void notEqual() { assertTrue(CheckFieldMethod.execute(transformContext, "name", "NE", "BOB")); assertTrue(CheckFieldMethod.execute(transformContext, "name", "!=", "BOB")); assertTrue(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.NE.toString(), "BOB")); assertTrue(CheckFieldMethod.execute(transformContext, "name", "NE", "Robert")); assertTrue(CheckFieldMethod.execute(transformContext, "name", CheckFieldMethod.Operator.NE.toString(), "Robert")); assertFalse(CheckFieldMethod.execute(transformContext, "name", "NE", "Bob")); } |
Evaluator { public boolean evaluateBoolean( final String expression ) throws IllegalArgumentException { return beval.evaluate( expression ); } Evaluator(); Evaluator( final TransformContext context ); boolean evaluateBoolean( final String expression ); double evaluateNumeric( final String expression ); void setContext( final TransformContext context ); } | @Test public void booleanComplex() { String expression; try { expression = "islast || equals(Working.record_type,\"22\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! islast || equals(Working.record_type,\"22\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "islast || equals(Working.field1,\"value1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "islast && equals(Working.field1,value1)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "islast && equals(Working.field1,\"value1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! islast && equals(Working.field1,\"value1\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "! islast && ! equals(Working.field1,\"value1\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "contextError && equals(currentRow,0)"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "! noRowsProcessed"; assertTrue(evaluator.evaluateBoolean(expression)); transformContext.setError(true); transformContext.setRow(0); expression = "contextError && equals(currentRow,0)"; assertTrue(evaluator.evaluateBoolean(expression)); transformContext.setError(false); expression = "! contextError && equals(currentRow,0)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "noRowsProcessed"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! islast && match(Working.userName,\"22\")"; expression = "! islast && match(Working.userName,\"22\")"; } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { transformContext.setError(false); transformContext.setRow(42); } }
@Test public void booleanContextError() { String expression; try { expression = "contextError"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "! contextError"; assertTrue(evaluator.evaluateBoolean(expression)); transformContext.setError(true); expression = "contextError"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! contextError"; assertFalse(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { transformContext.setError(false); } }
@Test public void booleanEmpty() { String expression; try { expression = "empty(\"Working.NullField\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "empty(Working.Field1)"; assert (evaluator.evaluateBoolean(expression)); expression = "empty(\"Working.field1\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "empty(Working.field1)"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "empty(\"field1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "empty(field1)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "empty(\"Working.Field1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "empty(Working.Field1)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "empty(string)"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "empty(\"string\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "empty(\" string \")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "empty(String)"; assertTrue(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void booleanEquals() { String expression; try { expression = "equals(5,5)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "equals(5,4)"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "equals(currentRow,42)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "equals(currentRow,43)"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "equals(Working.field1,value1)"; assertTrue(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void booleanExists() { String expression; try { expression = "exists(\"Source.RecordType\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "exists(\"Working.field1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "exists(\"field1\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "exists(\"Working.Field1\")"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "exists(\"Working.NullField\")"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "exists(field1)"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "exists(Working.Field1)"; assertFalse(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void booleanIsLast() { String expression; try { expression = "islast"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! islast"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "islast || false"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! islast || false"; assertFalse(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void booleanOperators() { String expression; try { expression = "true == true"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "true == false"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "true && false"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "true || false"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "!true"; assertFalse(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void booleanTransactionError() { String expression; try { expression = "transactionError"; assertFalse(evaluator.evaluateBoolean(expression)); expression = "! transactionError"; assertTrue(evaluator.evaluateBoolean(expression)); context.setError(true); expression = "transactionError"; assertTrue(evaluator.evaluateBoolean(expression)); expression = "! transactionError"; assertFalse(evaluator.evaluateBoolean(expression)); } catch (final Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { context.setError(false); } } |
Evaluator { public double evaluateNumeric( final String expression ) { return neval.evaluate( expression ); } Evaluator(); Evaluator( final TransformContext context ); boolean evaluateBoolean( final String expression ); double evaluateNumeric( final String expression ); void setContext( final TransformContext context ); } | @Test public void testEvaluateNumeric() { assertEquals(-2, evaluator.evaluateNumeric("2+-2^2"), 0.001); assertEquals(2, evaluator.evaluateNumeric("6 / 3"), 0.001); assertEquals(Double.POSITIVE_INFINITY, evaluator.evaluateNumeric("2/0"), 0.001); assertEquals(2, evaluator.evaluateNumeric("7 % 2.5"), 0.001); assertEquals(-1., evaluator.evaluateNumeric("-1"), 0.001); assertEquals(1., evaluator.evaluateNumeric("1"), 0.001); assertEquals(-3, evaluator.evaluateNumeric("1+-4"), 0.001); assertEquals(2, evaluator.evaluateNumeric("3-1"), 0.001); assertEquals(-4, evaluator.evaluateNumeric("-2^2"), 0.001); assertEquals(2, evaluator.evaluateNumeric("4^0.5"), 0.001); assertEquals(1, evaluator.evaluateNumeric("sin ( pi /2)"), 0.001); assertEquals(-1, evaluator.evaluateNumeric("cos(pi)"), 0.001); assertEquals(1, evaluator.evaluateNumeric("tan(pi/4)"), 0.001); assertEquals(Math.PI, evaluator.evaluateNumeric("acos( -1)"), 0.001); assertEquals(Math.PI / 2, evaluator.evaluateNumeric("asin(1)"), 0.001); assertEquals(Math.PI / 4, evaluator.evaluateNumeric("atan(1)"), 0.001); assertEquals(1, evaluator.evaluateNumeric("ln(e)"), 0.001); assertEquals(2, evaluator.evaluateNumeric("log(100)"), 0.001); assertEquals(-1, evaluator.evaluateNumeric("min(1,-1)"), 0.001); assertEquals(-1, evaluator.evaluateNumeric("min(8,3,1,-1)"), 0.001); assertEquals(11, evaluator.evaluateNumeric("sum(8,3,1,-1)"), 0.001); assertEquals(3, evaluator.evaluateNumeric("avg(8,3,1,0)"), 0.001); assertEquals(3, evaluator.evaluateNumeric("abs(-3)"), 0.001); assertEquals(3, evaluator.evaluateNumeric("ceil(2.45)"), 0.001); assertEquals(2, evaluator.evaluateNumeric("floor(2.45)"), 0.001); assertEquals(2, evaluator.evaluateNumeric("round(2.45)"), 0.001); assertEquals(evaluator.evaluateNumeric("tanh(5)"), evaluator.evaluateNumeric("sinh(5)/cosh(5)"), 0.001); assertEquals(-1, evaluator.evaluateNumeric("min(1,min(3+2,2))+-round(4.1)*0.5"), 0.001); final double rnd = evaluator.evaluateNumeric("random()"); assertTrue((rnd >= 0) && (rnd <= 1.0)); } |
Evaluator { public Evaluator() { } Evaluator(); Evaluator( final TransformContext context ); boolean evaluateBoolean( final String expression ); double evaluateNumeric( final String expression ); void setContext( final TransformContext context ); } | @Test public void testEvaluator() { final Evaluator subject = new Evaluator(); assertNotNull(subject); } |
Evaluator { public void setContext( final TransformContext context ) { beval.setContext( context ); neval.setContext( context ); } Evaluator(); Evaluator( final TransformContext context ); boolean evaluateBoolean( final String expression ); double evaluateNumeric( final String expression ); void setContext( final TransformContext context ); } | @Test public void testSetContext() { evaluator.setContext(transformContext); } |
OriginUri { URI uri() { return uri; } OriginUri(HttpCookie cookie, URI associated); } | @Test public void shouldOriginUriReturnAssociatedIfCookieUriIsEmpty() throws URISyntaxException { URI associated = new URI("http", "google.com", "/", ""); HttpCookie cookie = new HttpCookie("name", "value"); OriginUri uri = new OriginUri(cookie, associated); assertEquals(associated, uri.uri()); }
@Test public void shouldOriginUriReturnUriFromHttpCookie() throws URISyntaxException { URI associated = new URI("http", "google.com", "/", ""); HttpCookie cookie = new HttpCookie("name", "value"); cookie.setDomain("abc.xyz"); OriginUri uri = new OriginUri(cookie, associated); assertNotEquals(associated, uri.uri()); }
@Test public void shouldOriginUriProperlyFormatUri() throws URISyntaxException { URI associated = new URI("http", "google.com", "/", ""); HttpCookie cookie = new HttpCookie("name", "value"); cookie.setDomain("abc.xyz"); cookie.setPath("/home"); OriginUri uri = new OriginUri(cookie, associated); assertEquals("http: }
@Test public void shouldSkipDotWhileFormattingUri() throws URISyntaxException { URI associated = new URI("http", "google.com", "/", ""); HttpCookie cookie = new HttpCookie("name", "value"); cookie.setDomain(".abc.xyz"); OriginUri uri = new OriginUri(cookie, associated); assertEquals("http: } |
CookieTray implements CookieStore { @Override public synchronized void add(URI associatedUri, HttpCookie cookie) { URI uri = new OriginUri(cookie, associatedUri).uri(); Set<HttpCookie> targetCookies = cookiesCache.get(uri); if (targetCookies == null) { targetCookies = new HashSet<>(); cookiesCache.put(uri, targetCookies); } targetCookies.remove(cookie); targetCookies.add(cookie); persistCookie(uri, cookie); } CookieTray(SharedPreferences preferences); CookieTray(Context context); @Override synchronized void add(URI associatedUri, HttpCookie cookie); @Override synchronized List<HttpCookie> get(URI uri); @Override synchronized List<HttpCookie> getCookies(); @Override synchronized List<URI> getURIs(); @Override synchronized boolean remove(URI uri, HttpCookie cookie); @Override synchronized boolean removeAll(); } | @Test public void shouldAddCookieToSharedPreferences() throws URISyntaxException { URI uri = URI.create("http: CookieStore store = new CookieTray(preferences); HttpCookie httpCookie = new HttpCookie("name", "value"); store.add(uri, httpCookie); String cookieVal = new SerializableCookie(httpCookie).asString(); verify(editor).putString(uri.toString() + "|" + httpCookie.getName(), cookieVal); } |
CookieTray implements CookieStore { @Override public synchronized boolean remove(URI uri, HttpCookie cookie) { Set<HttpCookie> targetCookies = cookiesCache.get(uri); boolean cookieRemoved = targetCookies != null && targetCookies.remove(cookie); if (cookieRemoved) { removeFromPersistence(uri, cookie); } return cookieRemoved; } CookieTray(SharedPreferences preferences); CookieTray(Context context); @Override synchronized void add(URI associatedUri, HttpCookie cookie); @Override synchronized List<HttpCookie> get(URI uri); @Override synchronized List<HttpCookie> getCookies(); @Override synchronized List<URI> getURIs(); @Override synchronized boolean remove(URI uri, HttpCookie cookie); @Override synchronized boolean removeAll(); } | @Test public void shouldBeAbleToRemoveCookie() { addCookies(1, false); CookieStore store = new CookieTray(preferences); store.remove(URI.create("http: verify(editor).remove("http: } |
CookieTray implements CookieStore { @Override public synchronized List<HttpCookie> getCookies() { List<HttpCookie> cookies = new ArrayList<>(); for (URI storedUri : cookiesCache.keySet()) { cookies.addAll(getValidCookies(storedUri)); } return cookies; } CookieTray(SharedPreferences preferences); CookieTray(Context context); @Override synchronized void add(URI associatedUri, HttpCookie cookie); @Override synchronized List<HttpCookie> get(URI uri); @Override synchronized List<HttpCookie> getCookies(); @Override synchronized List<URI> getURIs(); @Override synchronized boolean remove(URI uri, HttpCookie cookie); @Override synchronized boolean removeAll(); } | @Test public void shouldReturnNoCookiesOnEmptyStore() { CookieStore store = new CookieTray(preferences); assertTrue(store.getCookies().isEmpty()); }
@Test public void shouldReturnAllCookies() { addCookies(10, false); CookieStore store = new CookieTray(preferences); assertEquals(10, store.getCookies().size()); }
@Test public void shouldFilterOutExpiredCookies() { addCookies(10, true); CookieStore store = new CookieTray(preferences); assertEquals(0, store.getCookies().size()); } |
CookieTray implements CookieStore { @Override public synchronized List<URI> getURIs() { return new ArrayList<>(cookiesCache.keySet()); } CookieTray(SharedPreferences preferences); CookieTray(Context context); @Override synchronized void add(URI associatedUri, HttpCookie cookie); @Override synchronized List<HttpCookie> get(URI uri); @Override synchronized List<HttpCookie> getCookies(); @Override synchronized List<URI> getURIs(); @Override synchronized boolean remove(URI uri, HttpCookie cookie); @Override synchronized boolean removeAll(); } | @Test public void shouldReturnNoUrisOnEmptyStore() { CookieStore store = new CookieTray(preferences); assertTrue(store.getURIs().isEmpty()); }
@Test public void shouldReturnStoredUris() { addCookies(7, false); CookieStore store = new CookieTray(preferences); assertEquals(7, store.getURIs().size()); } |
CookieTray implements CookieStore { @Override public synchronized List<HttpCookie> get(URI uri) { return getValidCookies(uri); } CookieTray(SharedPreferences preferences); CookieTray(Context context); @Override synchronized void add(URI associatedUri, HttpCookie cookie); @Override synchronized List<HttpCookie> get(URI uri); @Override synchronized List<HttpCookie> getCookies(); @Override synchronized List<URI> getURIs(); @Override synchronized boolean remove(URI uri, HttpCookie cookie); @Override synchronized boolean removeAll(); } | @Test public void shouldFilterCookiesOutByUri() { addCookies(10, false); CookieStore store = new CookieTray(preferences); assertEquals(1, store.get(URI.create("http: } |
StatusServer { public void shutdown() { try { log.info("StatusServer shutting down"); executor.shutdownNow(); } catch (Exception e) { log.error("Exception while shutting down: " + e.getMessage(), e); } } @Inject StatusServer(ServerConfig config, Injector injector); static ServletModule createJerseyServletModule(); void waitUntilStarted(); void start(); void shutdown(); } | @Test public void _2_connectionFailureShouldBeDetected() throws Exception { suroServer.getInjector().getInstance(InputManager.class).getInput("thrift").shutdown(); HttpResponse response = runQuery("surohealthcheck"); assertEquals(500, response.getStatusLine().getStatusCode()); } |
AlwaysFalseMessageFilter extends BaseMessageFilter { @Override public boolean apply(Object input) { return false; } private AlwaysFalseMessageFilter(); @Override boolean apply(Object input); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final AlwaysFalseMessageFilter INSTANCE; } | @Test public void testAlwaysFalse() { assertFalse(AlwaysFalseMessageFilter.INSTANCE.apply(DUMMY_INPUT)); } |
NotMessageFilter extends BaseMessageFilter { @Override public boolean apply(Object input) { return notPredicate.apply(input); } NotMessageFilter(MessageFilter filter); @Override boolean apply(Object input); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void testNotTrueIsFalse() { assertFalse(new NotMessageFilter(getTrueFilter()).apply(DUMMY_INPUT)); }
@Test public void testNotFalseIsTrue() { assertTrue(new NotMessageFilter(getFalseFilter()).apply(DUMMY_INPUT)); } |
MessageFilters { public static MessageFilter alwaysFalse() { return AlwaysFalseMessageFilter.INSTANCE; } private MessageFilters(); static MessageFilter alwaysTrue(); static MessageFilter alwaysFalse(); static MessageFilter or(MessageFilter...filters); static MessageFilter or(Iterable<MessageFilter> filters); static MessageFilter and(MessageFilter...filters); static MessageFilter and(Iterable<MessageFilter> filters); static MessageFilter not(MessageFilter filter); } | @Test public void testAlwaysFalseReturnsFalse() { assertFalse(alwaysFalse().apply(DUMMY_INPUT)); } |
MessageFilters { public static MessageFilter alwaysTrue(){ return AlwaysTrueMessageFilter.INSTANCE; } private MessageFilters(); static MessageFilter alwaysTrue(); static MessageFilter alwaysFalse(); static MessageFilter or(MessageFilter...filters); static MessageFilter or(Iterable<MessageFilter> filters); static MessageFilter and(MessageFilter...filters); static MessageFilter and(Iterable<MessageFilter> filters); static MessageFilter not(MessageFilter filter); } | @Test public void testAlwaysTrueReturnsTrue() { assertTrue(alwaysTrue().apply(DUMMY_INPUT)); } |
MessageFilters { public static MessageFilter not(MessageFilter filter) { return new NotMessageFilter(filter); } private MessageFilters(); static MessageFilter alwaysTrue(); static MessageFilter alwaysFalse(); static MessageFilter or(MessageFilter...filters); static MessageFilter or(Iterable<MessageFilter> filters); static MessageFilter and(MessageFilter...filters); static MessageFilter and(Iterable<MessageFilter> filters); static MessageFilter not(MessageFilter filter); } | @Test public void testNotAlwaysNegates(){ assertTrue(not(getFalseFilter()).apply(DUMMY_INPUT)); assertFalse(not(getTrueFilter()).apply(DUMMY_INPUT)); } |
MessageFilters { public static MessageFilter or(MessageFilter...filters) { return new OrMessageFilter(filters); } private MessageFilters(); static MessageFilter alwaysTrue(); static MessageFilter alwaysFalse(); static MessageFilter or(MessageFilter...filters); static MessageFilter or(Iterable<MessageFilter> filters); static MessageFilter and(MessageFilter...filters); static MessageFilter and(Iterable<MessageFilter> filters); static MessageFilter not(MessageFilter filter); } | @Test public void testOr() { assertTrue(or(getFalseFilter(), getFalseFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(or(getFalseFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } |
MessageFilters { public static MessageFilter and(MessageFilter...filters) { return new AndMessageFilter(filters); } private MessageFilters(); static MessageFilter alwaysTrue(); static MessageFilter alwaysFalse(); static MessageFilter or(MessageFilter...filters); static MessageFilter or(Iterable<MessageFilter> filters); static MessageFilter and(MessageFilter...filters); static MessageFilter and(Iterable<MessageFilter> filters); static MessageFilter not(MessageFilter filter); } | @Test public void testAnd(){ assertTrue(and(getTrueFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(and(getTrueFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } |
AndMessageFilter extends BaseMessageFilter { @Override public boolean apply(Object input) { return andPredicate.apply(input); } AndMessageFilter(MessageFilter... filters); AndMessageFilter(Iterable<? extends MessageFilter> filters); @Override boolean apply(Object input); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testAllAcceptancesLeadToAcceptance() { List<? extends MessageFilter> filters = ImmutableList.of( VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter()); AndMessageFilter filter = new AndMessageFilter(filters); assertTrue(filter.apply(VerificationUtil.DUMMY_INPUT)); }
@Test public void testOneRejectionLeadsToRejection() { List<? extends MessageFilter> filters = ImmutableList.of( VerificationUtil.getTrueFilter(), VerificationUtil.getTrueFilter(), VerificationUtil.getFalseFilter() ); AndMessageFilter filter = new AndMessageFilter(filters); assertFalse(filter.apply(VerificationUtil.DUMMY_INPUT)); }
@Test public void testAndMessageFilterShortcuts() { MessageFilter falseFilter = VerificationUtil.getFalseFilter(); MessageFilter trueFilter = VerificationUtil.getTrueFilter(); List<? extends MessageFilter> filters = ImmutableList.of( falseFilter, trueFilter ); assertFalse(new AndMessageFilter(filters).apply(VerificationUtil.DUMMY_INPUT)); verify(trueFilter, never()).apply(VerificationUtil.DUMMY_INPUT); } |
HealthCheck { @GET @Produces("text/plain") public synchronized String get() { try { if (inputManager.getInput("thrift") != null) { if (client == null) { client = getClient("localhost", config.getPort(), 5000); } ServiceStatus status = client.getStatus(); if (status != ServiceStatus.ALIVE) { throw new RuntimeException("NOT ALIVE!!!"); } } return "SuroServer - OK"; } catch (Exception e) { throw new RuntimeException("NOT ALIVE!!!"); } } @Inject HealthCheck(ServerConfig config, InputManager inputManager); @GET @Produces("text/plain") synchronized String get(); } | @Test public void test() throws TTransportException, IOException { InputManager inputManager = mock(InputManager.class); doReturn(mock(SuroInput.class)).when(inputManager).getInput("thrift"); HealthCheck healthCheck = new HealthCheck(new ServerConfig() { @Override public int getPort() { return suroServer.getServerPort(); } }, inputManager); healthCheck.get(); suroServer.getInjector().getInstance(InputManager.class).getInput("thrift").shutdown(); try { healthCheck.get(); fail("exception should be thrown"); } catch (RuntimeException e) { assertEquals(e.getMessage(), "NOT ALIVE!!!"); } } |
OrMessageFilter extends BaseMessageFilter { @Override public boolean apply(Object input) { return orPredicate.apply(input); } OrMessageFilter(MessageFilter... filters); OrMessageFilter(Iterable<? extends MessageFilter> filters); @Override boolean apply(Object input); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void testAllRejectionsLeadToRejection() { List<? extends MessageFilter> filters = ImmutableList.of(getFalseFilter(), getFalseFilter(), getFalseFilter()); OrMessageFilter filter = new OrMessageFilter(filters); assertFalse(filter.apply(DUMMY_INPUT)); }
@Test public void testOneAcceptanceLeadsToAcceptance() { List<? extends MessageFilter> filters = ImmutableList.of(getFalseFilter(), getTrueFilter(), getFalseFilter()); OrMessageFilter filter = new OrMessageFilter(filters); assertTrue(filter.apply(DUMMY_INPUT)); }
@Test public void testOrMessageFilterShortcuts() { MessageFilter falseFilter = getFalseFilter(); MessageFilter trueFilter = getTrueFilter(); List<? extends MessageFilter> filters = ImmutableList.of(trueFilter, falseFilter); assertTrue(new OrMessageFilter(filters).apply(DUMMY_INPUT)); verify(falseFilter, never()).apply(DUMMY_INPUT); } |
AlwaysTrueMessageFilter extends BaseMessageFilter { @Override public boolean apply(Object input) { return true; } private AlwaysTrueMessageFilter(); @Override boolean apply(Object input); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final AlwaysTrueMessageFilter INSTANCE; } | @Test public void test() { assertTrue(AlwaysTrueMessageFilter.INSTANCE.apply(DUMMY_INPUT)); } |
RoutingKeyFilter implements Filter { @Override public boolean doFilter(MessageContainer message) throws Exception { return filterPattern.matcher(message.getRoutingKey()).find(); } @JsonCreator RoutingKeyFilter(@JsonProperty(JSON_PROPERTY_REGEX) String regex); @JsonProperty(JSON_PROPERTY_REGEX) String getRegex(); @Override boolean doFilter(MessageContainer message); static final String TYPE; static final String JSON_PROPERTY_REGEX; } | @Test public void testDoFilter() throws Exception { RoutingKeyFilter filter = new RoutingKeyFilter("(?i)key"); MessageContainer container = makeMessageContainer("routingkEYname", null, null); assertTrue(filter.doFilter(container)); }
@Test public void negativeTest() throws Exception { RoutingKeyFilter filter = new RoutingKeyFilter("nomatch"); MessageContainer container = makeMessageContainer("routingkey", null, null); assertFalse(filter.doFilter(container)); } |
XPathFilter implements Filter { @Override public boolean doFilter(MessageContainer message) throws Exception { return filter.apply(converter.convert(message)); } @JsonCreator XPathFilter(
@JsonProperty(JSON_PROPERTY_FILTER) String expression,
@JsonProperty(JSON_PROPERTY_CONVERTER) MessageConverter converter); @Override boolean doFilter(MessageContainer message); @JsonProperty(JSON_PROPERTY_CONVERTER) MessageConverter getConverter(); @JsonProperty(JSON_PROPERTY_FILTER) String getExpression(); static final String TYPE; static final String JSON_PROPERTY_FILTER; static final String JSON_PROPERTY_CONVERTER; } | @Test public void testXPathFilterWorksWithMap() throws Exception { String path = " Integer value = 6; XPathFilter filter = new XPathFilter(String.format("xpath(\"%s\") > 5", path), new JsonMapConverter()); assertTrue(filter.doFilter(makeMessageContainer("key", path, value))); }
@Test public void testExistFilter() throws Exception { XPathFilter filter = new XPathFilter("xpath(\"data.fit.sessionId\") exists", new JsonMapConverter()); assertTrue(filter.doFilter(new DefaultMessageContainer(new Message( "routingKey", jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("data.fit.sessionId", "abc") .put("f1", "v1") .build())), jsonMapper))); assertFalse(filter.doFilter(new DefaultMessageContainer(new Message( "routingKey", jsonMapper.writeValueAsBytes( new ImmutableMap.Builder<String, Object>() .put("data.fit.sessionIdABC", "abc") .put("f1", "v1") .build())), jsonMapper))); } |
SuroService { @PostConstruct public void start() { try { statusServer.start(); sinkManager.initialStart(); inputManager.initialStart(); } catch (Exception e) { log.error("Exception while starting up server: " + e.getMessage(), e); Throwables.propagate(e); } } @Inject private SuroService(StatusServer statusServer, InputManager inputManager, SinkManager sinkManager); @PostConstruct void start(); @PreDestroy void shutdown(); } | @Test public void test() throws Exception { AtomicReference<Injector> injector = new AtomicReference<Injector>(); Properties properties = new Properties(); properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY, "{}"); properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY, "{\n" + " \"default\": {\n" + " \"type\": \"testsuroservice\"\n" + " }\n" + " }\n" + "}"); properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY, "[\n" + " {\n" + " \"type\": \"testsuroservice\"\n" + " }\n" + "]"); SuroServer.create(injector, properties, new SuroPlugin() { @Override protected void configure() { addInputType("testsuroservice", TestSuroServiceInput.class); addSinkType("testsuroservice", TestSuroServiceSink.class); } }); injector.get().getInstance(LifecycleManager.class).start(); latch.await(5000, TimeUnit.MILLISECONDS); assertTrue(inputOpened.get()); assertTrue(sinkOpened.get()); } |
FileBlockingQueue extends AbstractQueue<E> implements BlockingQueue<E> { @Override public Iterator<E> iterator() { return new Iterator<E>() { @Override public boolean hasNext() { return !isEmpty(); } @Override public E next() { try { E x = consumeElement(); return x; } catch (IOException e) { throw new RuntimeException(e); } } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported, use dequeue()"); } }; } FileBlockingQueue(
String path,
String name,
int gcPeriodInSec,
SerDe<E> serDe); FileBlockingQueue(
String path,
String name,
int gcPeriodInSec,
SerDe<E> serDe,
long sizeLimit); void gc(); void close(); @Override E poll(); @Override E peek(); @Override boolean offer(E e); @Override void put(E e); @Override boolean offer(E e, long timeout, TimeUnit unit); @Override E take(); @Override E poll(long timeout, TimeUnit unit); @Override int remainingCapacity(); @Override int drainTo(Collection<? super E> c); @Override int drainTo(Collection<? super E> c, int maxElements); @Override Iterator<E> iterator(); @Override int size(); } | @Test public void testOpenAndReadFromStart() throws IOException { final FileBlockingQueue<String> queue = getFileBlockingQueue(); createFile(queue, 3000); int count = 0; for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); }
@Test public void testOpenAndReadFromMark() throws IOException { final FileBlockingQueue<String> queue = getFileBlockingQueue(); createFile(queue, 3000); int count = 0; for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); count = 0; createFile(queue, 3000); for (String m : new Iterable<String>() { @Override public Iterator<String> iterator() { return queue.iterator(); } }) { assertEquals(m, "testString" + count); ++count; } assertEquals(count, 3000); } |
QueuedSink extends Thread { protected void initialize( String sinkId, MessageQueue4Sink queue4Sink, int batchSize, int batchTimeout, boolean pauseOnLongQueue) { this.sinkId = sinkId; this.queue4Sink = queue4Sink; this.batchSize = batchSize == 0 ? 1000 : batchSize; this.batchTimeout = batchTimeout == 0 ? 1000 : batchTimeout; this.pauseOnLongQueue = pauseOnLongQueue; throughput = new Meter(MonitorConfig.builder(sinkId + "_throughput_meter").build()); } long checkPause(); String getSinkId(); @Override void run(); void close(); @Monitor(name = "numOfPendingMessages", type = DataSourceType.GAUGE) long getNumOfPendingMessages(); static int MAX_PENDING_MESSAGES_TO_PAUSE; } | @Test public void synchronizedQueue() throws InterruptedException { final int queueCapacity = 0; final MemoryQueue4Sink queue = new MemoryQueue4Sink(queueCapacity); final AtomicInteger sentCount = new AtomicInteger(); QueuedSink sink = new QueuedSink() { @Override protected void beforePolling() throws IOException { } @Override protected void write(List<Message> msgList) throws IOException { sentCount.addAndGet(msgList.size()); } @Override protected void innerClose() throws IOException { } }; sink.initialize(queue, 100, 1000); sink.start(); int msgCount = 1000; int offered = 0; for (int i = 0; i < msgCount; ++i) { if (queue.offer(new Message("routingKey", ("message" + i).getBytes()))) { offered++; } } assertEquals(msgCount, offered); for (int i = 0; i < 20; ++i) { if (sentCount.get() < offered) { Thread.sleep(500); } } assertEquals(sentCount.get(), offered); } |
FileNameFormatter { public static String get(String dir) { StringBuilder sb = new StringBuilder(dir); if (!dir.endsWith("/")) { sb.append('/'); } sb.append(fmt.print(new DateTime())) .append(localHostAddr) .append(new UID().toString()); return sb.toString().replaceAll("[-:]", ""); } static String get(String dir); static String localHostAddr; } | @Test public void test() { String name = FileNameFormatter.get("/dir/"); System.out.println(name); assertEquals(name.indexOf("-"), -1); assertEquals(name.indexOf(":"), -1); } |
LocalFileSink extends QueuedSink implements Sink { public int cleanUp(boolean fetchAll) { return cleanUp(outputDir, fetchAll); } @JsonCreator LocalFileSink(
@JsonProperty("outputDir") String outputDir,
@JsonProperty("writer") FileWriter writer,
@JsonProperty("notice") Notice notice,
@JsonProperty("maxFileSize") long maxFileSize,
@JsonProperty("rotationPeriod") String rotationPeriod,
@JsonProperty("minPercentFreeDisk") int minPercentFreeDisk,
@JsonProperty("queue4Sink") MessageQueue4Sink queue4Sink,
@JsonProperty("batchSize") int batchSize,
@JsonProperty("batchTimeout") int batchTimeout,
@JsonProperty("pauseOnLongQueue") boolean pauseOnLongQueue,
@JacksonInject SpaceChecker spaceChecker); String getOutputDir(); @Override void open(); @Override void writeTo(MessageContainer message); @Override long checkPause(); @Override String recvNotice(); int cleanUp(boolean fetchAll); int cleanUp(String dir, boolean fetchAll); static String getFileExt(String fileName); @Override String getStat(); void deleteFile(String filePath); static final String EMPTY_ROUTING_KEY_REPLACEMENT; static final String TYPE; static final String suffix; static final String done; } | @Test public void testCleanUp() throws IOException, InterruptedException { String testdir = tempDir.newFolder().getAbsolutePath(); final int numFiles = 5; Set<String> filePathSet = new HashSet<String>(); for (int i = 0; i < numFiles; ++i) { String fileName = "testFile" + i + (i == numFiles - 1 ? LocalFileSink.suffix : LocalFileSink.done); File f = new File(testdir, fileName); f.createNewFile(); FileOutputStream o = new FileOutputStream(f); o.write(100 ); o.close(); if (i != numFiles - 1) { filePathSet.add(f.getAbsolutePath()); } } final String localFileSinkSpec = "{\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"rotationPeriod\": \"PT1m\",\n" + " \"outputDir\": \"" + testdir + "\"\n" + " }\n" + "}"; Thread.sleep(3000); ObjectMapper mapper = injector.getInstance(ObjectMapper.class); LocalFileSink sink = (LocalFileSink)mapper.readValue( localFileSinkSpec, new TypeReference<Sink>(){}); assertEquals(sink.cleanUp(testdir, false), numFiles -1); Set<String> filePathSetResult = new HashSet<String>(); for (int i = 0; i < numFiles - 1; ++i) { filePathSetResult.add(sink.recvNotice()); } assertEquals(filePathSet, filePathSetResult); assertEquals(sink.cleanUp(testdir, true), numFiles); } |
LocalFileSink extends QueuedSink implements Sink { public static String getFileExt(String fileName) { int dotPos = fileName.lastIndexOf('.'); if (dotPos != -1 && dotPos != fileName.length() - 1) { return fileName.substring(dotPos); } else { return null; } } @JsonCreator LocalFileSink(
@JsonProperty("outputDir") String outputDir,
@JsonProperty("writer") FileWriter writer,
@JsonProperty("notice") Notice notice,
@JsonProperty("maxFileSize") long maxFileSize,
@JsonProperty("rotationPeriod") String rotationPeriod,
@JsonProperty("minPercentFreeDisk") int minPercentFreeDisk,
@JsonProperty("queue4Sink") MessageQueue4Sink queue4Sink,
@JsonProperty("batchSize") int batchSize,
@JsonProperty("batchTimeout") int batchTimeout,
@JsonProperty("pauseOnLongQueue") boolean pauseOnLongQueue,
@JacksonInject SpaceChecker spaceChecker); String getOutputDir(); @Override void open(); @Override void writeTo(MessageContainer message); @Override long checkPause(); @Override String recvNotice(); int cleanUp(boolean fetchAll); int cleanUp(String dir, boolean fetchAll); static String getFileExt(String fileName); @Override String getStat(); void deleteFile(String filePath); static final String EMPTY_ROUTING_KEY_REPLACEMENT; static final String TYPE; static final String suffix; static final String done; } | @Test public void testGetFileExt() { assertEquals(LocalFileSink.getFileExt("abc.done"), ".done"); assertNull(LocalFileSink.getFileExt("abcdone")); assertNull(LocalFileSink.getFileExt("abcdone.")); } |
KafkaSink implements Sink { @Override public long checkPause() { if (blockOnBufferFull) { return 0; } else { double totalBytes = producer.metrics().get( new MetricName( "buffer-total-bytes", "producer-metrics", "desc", "client-id", props.getProperty("client.id"))).value(); double availableBytes = producer.metrics().get( new MetricName( "buffer-available-bytes", "producer-metrics", "desc", "client-id", props.getProperty("client.id"))).value(); double consumedMemory = totalBytes - availableBytes; double memoryRate = consumedMemory / totalBytes; if (memoryRate >= 0.5) { double outgoingRate = producer.metrics().get( new MetricName( "outgoing-byte-rate", "producer-metrics", "desc", "client-id", props.getProperty("client.id"))).value(); double throughputRate = Math.max(outgoingRate, 1.0); return (long) (consumedMemory / throughputRate * 1000); } else { return 0; } } } @JsonCreator KafkaSink(
@JsonProperty("client.id") String clientId,
@JsonProperty("metadata.broker.list") String brokerList,
@JsonProperty("bootstrap.servers") String bootstrapServers,
@JsonProperty("request.required.acks") Integer requiredAcks,
@JsonProperty("acks") String acks,
@JsonProperty("buffer.memory") long bufferMemory,
@JsonProperty("batch.size") int batchSize,
@JsonProperty("compression.codec") String codec,
@JsonProperty("compression.type") String compression,
@JsonProperty("retries") int retries,
@JsonProperty("block.on.buffer.full") boolean blockOnBufferFull,
@JsonProperty("metadata.waiting.queue.size") int metadataWaitingQueueSize,
@JsonProperty("kafka.etc") Properties etcProps,
@JsonProperty("keyTopicMap") Map<String, String> keyTopicMap,
@JacksonInject KafkaRetentionPartitioner retentionPartitioner); void setRecordCounterListener(Action3 action); @Override void writeTo(final MessageContainer message); @Override void open(); @Override void close(); @Override String recvNotice(); @Override String getStat(); @Override long getNumOfPendingMessages(); @Override long checkPause(); final static String TYPE; } | @Test public void testCheckPause() throws IOException, InterruptedException { TopicCommand.createTopic(zk.getZkClient(), new TopicCommand.TopicCommandOptions(new String[]{ "--zookeeper", "dummy", "--create", "--topic", TOPIC_NAME + "check_pause", "--replication-factor", "2", "--partitions", "1"})); String description = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"" + kafkaServer.getBrokerListStr() + "\",\n" + " \"acks\": 1,\n" + " \"buffer.memory\": 1000,\n" + " \"batch.size\": 1000\n" + "}"; final KafkaSink sink = jsonMapper.readValue(description, new TypeReference<Sink>(){}); sink.open(); final AtomicBoolean exceptionCaught = new AtomicBoolean(false); final AtomicBoolean checkPaused = new AtomicBoolean(false); final AtomicBoolean pending = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); sink.setRecordCounterListener(new Action3<Long, Long, Long>() { @Override public void call(Long queued, Long sent, Long dropped) { if (dropped > 0) { exceptionCaught.set(true); if (sink.checkPause() > 0) { checkPaused.set(true); } if (sink.getNumOfPendingMessages() > 0) { pending.set(true); } latch.countDown(); } } }); for (int i = 0; i < 100; ++i) { sink.writeTo(new DefaultMessageContainer(new Message(TOPIC_NAME + "check_pause", getBigData()), jsonMapper)); } assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(exceptionCaught.get()); assertTrue(checkPaused.get()); assertTrue(pending.get()); } |
ElasticSearchSink extends ThreadPoolQueuedSink implements Sink { public void recover(Message message) { IndexInfo info = indexInfo.create(message); HttpResponse response = null; try { response = client.executeWithLoadBalancer( HttpRequest.newBuilder() .verb(HttpRequest.Verb.POST) .setRetriable(true) .uri(indexInfo.getIndexUri(info)) .entity(indexInfo.getSource(info)) .build()); if (response.getStatus() / 100 != 2) { Servo.getCounter( MonitorConfig.builder("unrecoverableRow") .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, message.getRoutingKey()) .build()).increment(); } } catch (Exception e) { log.error("Exception while recover: " + e.getMessage(), e); Servo.getCounter("recoverException").increment(); if (reEnqueueOnException) { writeTo(new DefaultMessageContainer(message, jsonMapper)); } else { Servo.getCounter( MonitorConfig.builder("unrecoverableRow") .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, message.getRoutingKey()) .build()).increment(); } } finally { if (response != null) { response.close(); } } } ElasticSearchSink(
@JsonProperty("clientName") String clientName,
@JsonProperty("queue4Sink") MessageQueue4Sink queue4Sink,
@JsonProperty("batchSize") int batchSize,
@JsonProperty("batchTimeout") int batchTimeout,
@JsonProperty("addressList") List<String> addressList,
@JsonProperty("indexInfo") @JacksonInject IndexInfoBuilder indexInfo,
@JsonProperty("jobQueueSize") int jobQueueSize,
@JsonProperty("corePoolSize") int corePoolSize,
@JsonProperty("maxPoolSize") int maxPoolSize,
@JsonProperty("jobTimeout") long jobTimeout,
@JsonProperty("sleepOverClientException") int sleepOverClientException,
@JsonProperty("ribbon.etc") Properties ribbonEtc,
@JsonProperty("reEnqueueOnException") boolean reEnqueueOnException,
@JacksonInject ObjectMapper jsonMapper,
@JacksonInject RestClient client); @Override void writeTo(MessageContainer message); @Override void open(); @Override String recvNotice(); @Override String getStat(); void recover(Message message); static final String TYPE; } | @Test public void testRecover() throws Exception { ObjectMapper jsonMapper = new DefaultObjectMapper(); ElasticSearchSink sink = new ElasticSearchSink( "default", null, 10, 1000, Lists.newArrayList("localhost:" + getPort()), null, 0,0,0,0, 0, null, false, jsonMapper, null ); sink.open(); DateTime dt = new DateTime("2014-10-12T12:12:12.000Z"); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .put("f3", "v3") .put("ts", dt.getMillis()) .build(); String routingKey = "topicrecover"; String index = "topicrecover"; List<Message> msgList = new ArrayList<>(); int msgCount = 100; for (int i = 0; i < msgCount; ++i) { msgList.add(new Message(routingKey, jsonMapper.writeValueAsBytes(msg))); } for (Message m : msgList) { sink.recover(m); } refresh(); CountResponse countResponse = client().count(new CountRequest(index)).actionGet(); assertEquals(countResponse.getCount(), 100); } |
DefaultIndexInfoBuilder implements IndexInfoBuilder { @Override public IndexInfo create(final Message msg) { try { final Map<String, Object> msgMap; if (dataConverter != null) { msgMap = dataConverter.convert((Map<String, Object>) jsonMapper.readValue(msg.getPayload(), type)); } else { msgMap = jsonMapper.readValue(msg.getPayload(), type); } return new IndexInfo() { private long ts = 0; @Override public String getIndex() { String index = indexMap.get(msg.getRoutingKey()); if (index == null) { index = msg.getRoutingKey(); } return index + indexSuffixFormatter.format(this); } @Override public String getType() { String type = typeMap.get(msg.getRoutingKey()); return type == null ? "default" : type; } @Override public Object getSource() { if (dataConverter != null) { return msgMap; } else { return new String(msg.getPayload()); } } @Override public String getId() { if (idFieldsMap == null || !idFieldsMap.containsKey(msg.getRoutingKey())) { return null; } else { StringBuilder sb = new StringBuilder(); for (String id : idFieldsMap.get(msg.getRoutingKey())) { if (id.startsWith("ts_")) { sb.append(TimestampSlice.valueOf(id).get(getTimestamp())); } else { sb.append(msgMap.get(id)); } } return sb.toString(); } } @Override public long getTimestamp() { if (ts == 0 && timestampField != null) { ts = timestampField.get(msgMap); } return ts; } }; } catch (Exception e) { log.error("Exception on parsing message", e); return null; } } @JsonCreator DefaultIndexInfoBuilder(
@JsonProperty("indexTypeMap") Map<String, String> indexTypeMap,
@JsonProperty("idFields") Map<String, List<String>> idFieldsMap,
@JsonProperty("timestamp") TimestampField timestampField,
@JsonProperty("indexSuffixFormatter") IndexSuffixFormatter indexSuffixFormatter,
@JacksonInject DataConverter dataConverter,
@JacksonInject ObjectMapper jsonMapper
); @Override IndexInfo create(final Message msg); @Override String getActionMetadata(IndexInfo info); @Override String getSource(IndexInfo info); @Override String getIndexUri(IndexInfo info); @Override String getCommand(); } | @Test public void shouldReturnNullOnParsingFailure() { DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( null, null, null, null, null, jsonMapper); assertNull(builder.create(new Message("routingkey", "message".getBytes()))); }
@Test public void shouldNullOrEmptyIndexTypeMapReturnRoutingKey() throws JsonProcessingException { DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( null, null, null, null, null, jsonMapper); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>().put("f1", "v1").build(); IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getIndex(), "routingkey"); assertEquals(info.getType(), "default"); }
@Test public void shouldIndexTypeMapReturnSetting() throws JsonProcessingException { DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( new ImmutableMap.Builder<String, String>() .put("routingkey1", "index1:type1") .put("routingkey2", "index2").build(), null, null, null, null, jsonMapper); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>().put("f1", "v1").build(); IndexInfo info = builder.create(new Message("routingkey1", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getIndex(), "index1"); assertEquals(info.getType(), "type1"); info = builder.create(new Message("routingkey2", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getIndex(), "index2"); assertEquals(info.getType(), "default"); }
@Test public void shouldIndexFormatterWorkWithTimestampField() throws JsonProcessingException { Properties props = new Properties(); props.put("dateFormat", "YYYYMMdd"); DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( new ImmutableMap.Builder<String, String>() .put("routingkey1", "index1:type1") .put("routingkey2", "index2").build(), null, new TimestampField("ts", null), new IndexSuffixFormatter("date", props), null, jsonMapper); DateTime dt = new DateTime("2014-10-12T00:00:00.000Z"); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("ts", dt.getMillis()) .put("f1", "v1").build(); IndexInfo info = builder.create(new Message("routingkey1", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getIndex(), "index120141012"); assertEquals(info.getType(), "type1"); info = builder.create(new Message("routingkey2", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getIndex(), "index220141012"); assertEquals(info.getType(), "default"); }
@Test public void shouldGetIdReturnNullOnEmptyList() throws JsonProcessingException { DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( null, null, null, null, null, jsonMapper); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("f1", "v1").build(); IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertNull(info.getId()); builder = new DefaultIndexInfoBuilder( null, new ImmutableMap.Builder<String, List<String>>().build(), null, null, null, jsonMapper); info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertNull(info.getId()); }
@Test public void shouldGetIdReturnsConcatenatedStr() throws JsonProcessingException { Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .put("f3", "v3") .build(); DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( null, new ImmutableMap.Builder<String, List<String>>().put("routingkey", Lists.newArrayList("f1", "f2")).build(), null, null, null, jsonMapper); IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getId(), "v1v2"); }
@Test public void shouldGetIdReturnsConcatedStrWithTimeslice() throws JsonProcessingException { DateTime dt = new DateTime("2014-10-12T12:12:12.000Z"); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .put("f3", "v3") .put("ts", dt.getMillis()) .build(); DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder( null, new ImmutableMap.Builder<String, List<String>>().put("routingkey", Lists.newArrayList("f1", "f2", "ts_minute")).build(), new TimestampField("ts", null), null, null, jsonMapper); IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getId(), ("v1v2" + dt.getMillis() / 60000)); }
@Test public void testCreation() throws IOException { String desc = "{\n" + " \"type\": \"default\",\n" + " \"indexTypeMap\":{\"routingkey1\":\"index1:type1\", \"routingkey2\":\"index2:type2\"},\n" + " \"idFields\":{\"routingkey\": [\"f1\", \"f2\", \"ts_minute\"]},\n" + " \"timestamp\": {\"field\":\"ts\"},\n" + " \"indexSuffixFormatter\":{\"type\": \"date\", \"properties\":{\"dateFormat\":\"YYYYMMdd\"}}\n" + "}"; jsonMapper.setInjectableValues(new InjectableValues() { @Override public Object findInjectableValue( Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance ) { if (valueId.equals(ObjectMapper.class.getCanonicalName())) { return jsonMapper; } else { return null; } } }); DateTime dt = new DateTime("2014-10-12T12:12:12.000Z"); Map<String, Object> msg = new ImmutableMap.Builder<String, Object>() .put("f1", "v1") .put("f2", "v2") .put("f3", "v3") .put("ts", dt.getMillis()) .build(); IndexInfoBuilder builder = jsonMapper.readValue(desc, new TypeReference<IndexInfoBuilder>(){}); IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg))); assertEquals(info.getId(), ("v1v2" + dt.getMillis() / 60000)); } |
PathValueMessageFilter extends BaseMessageFilter { @SuppressWarnings("unchecked") @Override public boolean apply(Object input) { JXPathContext jxpath = JXPathContext.newContext(input); jxpath.setLenient(true); Object value = jxpath.getValue(xpath); return predicate.apply(value); } PathValueMessageFilter(String path, ValuePredicate predicate); @SuppressWarnings("unchecked") @Override boolean apply(Object input); String getXpath(); ValuePredicate getPredicate(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void testPositiveSelection() { MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); when(requestTrace.getClientInfoHostName()).thenReturn("localhost"); Map<String, Object> clientInfoMap = Maps.newHashMap(); clientInfoMap.put("clientName", "client"); clientInfoMap.put("clientId", (long) 10); when(requestTrace.getClientInfoMap()).thenReturn(clientInfoMap); MessageFilter filter = new PathValueMessageFilter(" assertTrue("Filter should return true as the client ID is 10, greater than 5", filter.apply(requestTrace)); filter = new PathValueMessageFilter(" assertTrue("Filter should return true as client name is 'client'", filter.apply(requestTrace)); filter = new PathValueMessageFilter(" assertTrue("Filter should return tre as clientInfoHostName is localhost", filter.apply(requestTrace)); }
@Test public void testNonExistentValueShouldBeFiltered(){ MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); MessageFilter filter = new PathValueMessageFilter(" assertFalse(filter.apply(requestTrace)); }
@Test public void testNullValueCanBeAccepted(){ MockRequestTrace requestTrace = Mockito.mock(MockRequestTrace.class); MessageFilter filter = new PathValueMessageFilter(" assertTrue(filter.apply(requestTrace)); } |
TimestampField { public long get(Map<String, Object> msg) { Object value = msg.get(fieldName); if (value instanceof Number) { return ((Number) value).longValue(); } return formatter.parser().parseMillis(value.toString()); } @JsonCreator TimestampField(@JsonProperty("field") String fieldName, @JsonProperty("format") String format); long get(Map<String, Object> msg); } | @Test public void shouldNullFormatReturnsLongTS() { TimestampField field = new TimestampField("ts", null); long ts = System.currentTimeMillis(); assertEquals( field.get( new ImmutableMap.Builder<String, Object>() .put("ts", ts) .put("field1", "value1").build()), ts); assertEquals( field.get( new ImmutableMap.Builder<String, Object>() .put("ts", "2014-04-05T00:00:00.000Z") .put("field1", "value1").build()), new DateTime("2014-04-05T00:00:00.000Z").getMillis()); }
@Test(expected=IllegalArgumentException.class) public void shouldNonNullFormatThrowsException() { TimestampField field = new TimestampField("ts", "YYYY-MM-DD"); long ts = System.currentTimeMillis(); assertEquals( field.get( new ImmutableMap.Builder<String, Object>() .put("ts", ts) .put("field1", "value1").build()), ts); field.get( new ImmutableMap.Builder<String, Object>() .put("ts", "2014-04-05T00:00:00.000Z") .put("field1", "value1").build()); }
@Test public void testFormat() { TimestampField field = new TimestampField("ts", "EEE MMM dd HH:mm:ss zzz YYYY"); assertEquals( field.get(new ImmutableMap.Builder<String, Object>() .put("ts", "Fri Oct 03 18:25:08 GMT 2014") .put("field1", "value1").build()), new DateTime("2014-10-03T18:25:08.000Z").getMillis()); }
@Test public void testFormat2() { TimestampField field = new TimestampField("ts", "YYYY-MM-dd HH:mm:ss.SSS"); assertEquals( field.get(new ImmutableMap.Builder<String, Object>() .put("ts", "2014-10-17 19:53:26.001") .put("field1", "value1").build()), new DateTime("2014-10-17T19:53:26.001Z").getMillis()); } |
IndexSuffixFormatter { public String format(IndexInfo info) { return formatter.apply(info); } @JsonCreator IndexSuffixFormatter(
@JsonProperty("type") String type,
@JsonProperty("properties") Properties props); String format(IndexInfo info); } | @Test public void shouldNullTypeReturnsEmptyString() { IndexSuffixFormatter formatter = new IndexSuffixFormatter(null, null); assertEquals(formatter.format(any(IndexInfo.class)), ""); }
@Test public void shouldDateTypeReturnsCorrectOne() { System.setProperty("user.timezone", "GMT"); Properties props = new Properties(); props.put("dateFormat", "YYYYMMdd"); DateTime dt = new DateTime("2014-10-12T00:00:00.000Z"); IndexSuffixFormatter formatter = new IndexSuffixFormatter("date", props); IndexInfo info = mock(IndexInfo.class); doReturn(dt.getMillis()).when(info).getTimestamp(); assertEquals(formatter.format(info), "20141012"); }
@Test public void testWeeklyRepresentation() { System.setProperty("user.timezone", "GMT"); Properties props = new Properties(); props.put("dateFormat", "YYYYMM_ww"); DateTime dt = new DateTime("2014-10-12T00:00:00.000Z"); IndexSuffixFormatter formatter = new IndexSuffixFormatter("date", props); IndexInfo info = mock(IndexInfo.class); doReturn(dt.getMillis()).when(info).getTimestamp(); assertEquals(formatter.format(info), "201410_41"); } |
ConnectionPool { @Monitor(name = "PoolSize", type = DataSourceType.GAUGE) public int getPoolSize() { return connectionList.size(); } @Inject ConnectionPool(ClientConfig config, ILoadBalancer lb); @PreDestroy void shutdown(); @Monitor(name = "PoolSize", type = DataSourceType.GAUGE) int getPoolSize(); int getOutPoolSize(); void populateClients(); SuroConnection chooseConnection(); void endConnection(SuroConnection connection); void markServerDown(SuroConnection connection); } | @Test public void shouldBePopulatedWithNumberOfServersOnLessSenderThreads() throws Exception { props.setProperty(ClientConfig.ASYNC_SENDER_THREADS, "1"); createInjector(); ILoadBalancer lb = mock(ILoadBalancer.class); List<Server> servers = new LinkedList<Server>(); for (SuroServer4Test suroServer4Test : this.servers) { servers.add(new Server("localhost", suroServer4Test.getPort())); } when(lb.getServerList(true)).thenReturn(servers); ConnectionPool pool = new ConnectionPool(injector.getInstance(ClientConfig.class), lb); assertTrue(pool.getPoolSize() >= 1); for (int i = 0; i < 10; ++i) { if (pool.getPoolSize() != 3) { Thread.sleep(1000); } } assertEquals(pool.getPoolSize(), 3); }
@Test public void shouldBePopulatedWithNumberOfServersOnMoreSenderThreads() throws Exception { props.setProperty(ClientConfig.ASYNC_SENDER_THREADS, "10"); createInjector(); ILoadBalancer lb = mock(ILoadBalancer.class); List<Server> servers = new LinkedList<Server>(); for (SuroServer4Test suroServer4Test : this.servers) { servers.add(new Server("localhost", suroServer4Test.getPort())); } when(lb.getServerList(true)).thenReturn(servers); ConnectionPool pool = new ConnectionPool(injector.getInstance(ClientConfig.class), lb); assertEquals(pool.getPoolSize(), 3); }
@Test public void shouldPopulationFinishedOnTimeout() throws Exception { shutdownServers(servers); createInjector(); final ILoadBalancer lb = mock(ILoadBalancer.class); List<Server> servers = new LinkedList<Server>(); for (SuroServer4Test suroServer4Test : this.servers) { servers.add(new Server("localhost", suroServer4Test.getPort())); } when(lb.getServerList(true)).thenReturn(servers); final AtomicBoolean passed = new AtomicBoolean(false); Thread t = new Thread(new Runnable() { @Override public void run() { ConnectionPool pool = new ConnectionPool(injector.getInstance(ClientConfig.class), lb); assertEquals(pool.getPoolSize(), 0); passed.set(true); } }); t.start(); t.join((servers.size() + 1) * injector.getInstance(ClientConfig.class).getConnectionTimeout()); assertTrue(passed.get()); } |
SuroPing extends AbstractLoadBalancerPing { public boolean isAlive(Server server) { TSocket socket = null; TFramedTransport transport = null; try { socket = new TSocket(server.getHost(), server.getPort(), 2000); socket.getSocket().setTcpNoDelay(true); socket.getSocket().setKeepAlive(true); socket.getSocket().setSoLinger(true, 0); transport = new TFramedTransport(socket); transport.open(); return true; } catch (TTransportException e) { logger.warn("Ping {}", e.getMessage()); return false; } catch (SocketException e) { logger.warn("Ping {}", e.getMessage()); return false; } finally { close(transport); close(socket); } } SuroPing(); boolean isAlive(Server server); @Override void initWithNiwsConfig(IClientConfig clientConfig); } | @Test public void pingTest() throws Exception { final SuroServer4Test server4Test = new SuroServer4Test(); server4Test.start(); SuroPing ping = new SuroPing(); Server server = new Server("localhost", server4Test.getPort()); assertEquals(true, ping.isAlive(server)); server4Test.shutdown(); }
@Test public void pingFailTest() throws Exception { SuroPing ping = new SuroPing(); Server server = new Server("localhost", 7901); assertEquals(false, ping.isAlive(server)); } |
AsyncSuroSender implements Runnable { public void run() { boolean sent = false; boolean retried = false; long startTS = System.currentTimeMillis(); for (int i = 0; i < config.getRetryCount(); ++i) { ConnectionPool.SuroConnection connection = connectionPool.chooseConnection(); if (connection == null) { continue; } try { Result result = connection.send(messageSet); if (result != null && result.getResultCode() == ResultCode.OK && result.isSetMessage()) { sent = true; connectionPool.endConnection(connection); retried = i > 0; break; } else { log.error("Server is not stable: " + connection.getServer().toString()); connectionPool.markServerDown(connection); try { Thread.sleep(Math.min(i + 1, 5) * 100); } catch (InterruptedException e) {} } } catch (Exception e) { log.error("Exception in send: " + e.getMessage(), e); connectionPool.markServerDown(connection); client.updateSenderException(); } } if (sent){ client.updateSendTime(System.currentTimeMillis() - startTS); client.updateSentDataStats(messageSet, retried); } else { for (Message m : new MessageSetReader(messageSet)) { client.restore(m); } } } AsyncSuroSender(
TMessageSet messageSet,
AsyncSuroClient client,
ClientConfig config); void run(); TMessageSet getMessageSet(); } | @Test public void test() { AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class); AsyncSuroSender sender = new AsyncSuroSender( TestConnectionPool.createMessageSet(100), client, injector.getInstance(ClientConfig.class)); sender.run(); assertEquals(client.getSentMessageCount(), 100); TestConnectionPool.checkMessageSetCount(servers, 1, false); }
@Test public void testRestore() throws InterruptedException { AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class); for (SuroServer4Test c : servers) { c.setTryLater(); } AsyncSuroSender sender = new AsyncSuroSender( TestConnectionPool.createMessageSet(600), client, injector.getInstance(ClientConfig.class)); sender.run(); assertEquals(client.getSentMessageCount(), 0); assertTrue(client.getRestoredMessageCount() >= 600); for (SuroServer4Test c : servers) { c.cancelTryLater(); } injector.getInstance(ConnectionPool.class).populateClients(); while (client.getSentMessageCount() < 600) { System.out.println("sent: " + client.getSentMessageCount()); Thread.sleep(1000); } client.shutdown(); TestConnectionPool.checkMessageCount(servers, 600); } |
AsyncSuroClient implements ISuroClient { public void restore(Message message) { restoredMessages.incrementAndGet(); DynamicCounter.increment( MonitorConfig.builder(TagKey.RESTORED_COUNT) .withTag(TagKey.APP, config.getApp()) .withTag(TagKey.DATA_SOURCE, message.getRoutingKey()) .build()); for (Listener listener : listeners) { listener.restoredCallback(); } send(message); } @Inject AsyncSuroClient(
ClientConfig config,
Queue4Client messageQueue,
ConnectionPool connectionPool); @Override long getLostMessageCount(); @Monitor(name = "MessageQueueSize", type = DataSourceType.GAUGE) @Override long getNumOfPendingMessages(); @Override long getSentMessageCount(); long getRestoredMessageCount(); long getRetriedCount(); @Override void send(Message message); void restore(Message message); @PreDestroy void shutdown(); void updateSendTime(long sendTime); void updateSentDataStats(TMessageSet messageSet, boolean retried); ConnectionPool getConnectionPool(); void updateSenderException(); void addListener(Listener listener); static final String asyncRateLimitConfig; } | @Test public void testRestore() throws Exception { Properties props = new Properties(); props.setProperty(ClientConfig.RETRY_COUNT, "1"); props.setProperty(ClientConfig.ASYNC_TIMEOUT, "1"); setupFile(props); int messageCount = 3; AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class); final CountDownLatch restoreLatch = new CountDownLatch(messageCount / 3); final CountDownLatch sentLatch = new CountDownLatch(messageCount); client.addListener(new AsyncSuroClient.Listener() { @Override public void sentCallback(int count) { for (int i = 0; i < count; ++i) { sentLatch.countDown(); } } @Override public void restoredCallback() { restoreLatch.countDown(); } @Override public void lostCallback(int count) { fail("should not be lost"); } @Override public void retriedCallback() { } }); for (SuroServer4Test c : servers) { c.setTryLater(); } for (int i = 0; i < messageCount; ++i) { client.send(new Message("routingKey", "testMessage".getBytes())); } restoreLatch.await(10, TimeUnit.SECONDS); assertEquals(restoreLatch.getCount(), 0); for (SuroServer4Test c : servers) { c.cancelTryLater(); } injector.getInstance(ConnectionPool.class).populateClients(); sentLatch.await(60, TimeUnit.SECONDS); assertEquals(client.getSentMessageCount(), messageCount); assertEquals(client.getLostMessageCount(), 0); client.shutdown(); TestConnectionPool.checkMessageCount(servers, messageCount); } |
JsonLine implements RecordParser { @Override public List<MessageContainer> parse(String data) { if (routingKey != null) { return new ImmutableList.Builder<MessageContainer>() .add(new DefaultMessageContainer( new Message(routingKey, data.getBytes()), jsonMapper)) .build(); } else { try { Map<String, Object> record = jsonMapper.readValue(data, S3Consumer.typeReference); String routingKeyOnRecord = record.get(routingKeyField).toString(); if (Strings.isNullOrEmpty(routingKeyOnRecord)) { routingKeyOnRecord = routingKey; } if (!Strings.isNullOrEmpty(routingKeyOnRecord)) { return new ImmutableList.Builder<MessageContainer>() .add(new DefaultMessageContainer( new Message(routingKeyOnRecord, data.getBytes()), jsonMapper)) .build(); } else { return new ArrayList<MessageContainer>(); } } catch (IOException e) { log.error("Exception on parsing: " + e.getMessage(), e); return new ArrayList<MessageContainer>(); } } } @JsonCreator JsonLine(
@JsonProperty("routingKey") String routingKey,
@JsonProperty("routingKeyField") String routingKeyField,
@JacksonInject ObjectMapper jsonMapper
); @Override List<MessageContainer> parse(String data); static final String TYPE; } | @Test public void shouldReturnStaticRoutingKey() throws Exception { ObjectMapper jsonMapper = new DefaultObjectMapper(); JsonLine jsonLine = new JsonLine( "staticRoutingKey", null, new DefaultObjectMapper()); Map<String, Object> msgMap = new ImmutableMap.Builder<String, Object>().put("f1", "v1").put("f2", "v2").build(); List<MessageContainer> messages = jsonLine.parse(jsonMapper.writeValueAsString(msgMap)); assertEquals(messages.size(), 1); assertEquals(messages.get(0).getRoutingKey(), "staticRoutingKey"); assertEquals(messages.get(0).getEntity(S3Consumer.typeReference), msgMap); }
@Test public void shouldReturnRoutingKeyField() throws Exception { ObjectMapper jsonMapper = new DefaultObjectMapper(); JsonLine jsonLine = new JsonLine( null, "f1", new DefaultObjectMapper()); Map<String, Object> msgMap = new ImmutableMap.Builder<String, Object>().put("f1", "v1").put("f2", "v2").build(); List<MessageContainer> messages = jsonLine.parse(jsonMapper.writeValueAsString(msgMap)); assertEquals(messages.size(), 1); assertEquals(messages.get(0).getRoutingKey(), "v1"); assertEquals(messages.get(0).getEntity(S3Consumer.typeReference), msgMap); }
@Test public void shouldReturnStaticRoutingKeyOnNonExistingRoutingKeyField() throws Exception { ObjectMapper jsonMapper = new DefaultObjectMapper(); JsonLine jsonLine = new JsonLine( "defaultRoutingKey", "f1", new DefaultObjectMapper()); Map<String, Object> msgMap = new ImmutableMap.Builder<String, Object>().put("f3", "v3").put("f2", "v2").build(); List<MessageContainer> messages = jsonLine.parse(jsonMapper.writeValueAsString(msgMap)); assertEquals(messages.size(), 1); assertEquals(messages.get(0).getRoutingKey(), "defaultRoutingKey"); assertEquals(messages.get(0).getEntity(S3Consumer.typeReference), msgMap); }
@Test public void testWithNonParseableMessage() throws Exception { JsonLine jsonLine = new JsonLine( "defaultRoutingKey", "f1", new DefaultObjectMapper()); List<MessageContainer> messages = jsonLine.parse("non_parseable_msg"); assertEquals(messages.size(), 1); assertEquals(messages.get(0).getRoutingKey(), "defaultRoutingKey"); try { messages.get(0).getEntity(S3Consumer.typeReference); assertEquals(messages.get(0).getEntity(String.class), "non_parseable_msg"); fail("exception should be thrown"); } catch (Exception e) {} jsonLine = new JsonLine( null, "f1", new DefaultObjectMapper()); assertEquals(jsonLine.parse("non_parseable_msg").size(), 0); } |
GrantAcl { public GrantAcl(RestS3Service s3Service, String s3Acl, int s3AclRetries) { this.s3Service = s3Service; this.s3Acl = s3Acl; this.s3AclRetries = s3AclRetries; } GrantAcl(RestS3Service s3Service, String s3Acl, int s3AclRetries); boolean grantAcl(S3Object object); } | @Test public void test() throws Exception { RestS3Service s3Service = mock(RestS3Service.class); AccessControlList acl = new AccessControlList(); doReturn(acl).when(s3Service).getObjectAcl("bucket", "key"); doNothing().when(s3Service).putObjectAcl("bucket", "key", acl); GrantAcl grantAcl = new GrantAcl(s3Service, "1,2,3", 1); S3Object obj = new S3Object("key"); obj.setBucketName("bucket"); obj.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL); assertTrue(grantAcl.grantAcl(obj)); Set<GrantAndPermission> grants = new HashSet<GrantAndPermission>(Arrays.asList(acl.getGrantAndPermissions())); assertEquals(grants.size(), 3); Set<GrantAndPermission> grantSet = new HashSet<GrantAndPermission>(); for (int i = 1; i <= 3; ++i) { grantSet.add(new GrantAndPermission(new CanonicalGrantee(Integer.toString(i)), Permission.PERMISSION_READ)); } } |
S3FileSink extends RemoteFileSink { @Override public String recvNotice() { return notice.recv(); } @JsonCreator S3FileSink(
@JsonProperty("localFileSink") LocalFileSink localFileSink,
@JsonProperty("bucket") String bucket,
@JsonProperty("s3Endpoint") String s3Endpoint,
@JsonProperty("maxPartSize") long maxPartSize,
@JsonProperty("concurrentUpload") int concurrentUpload,
@JsonProperty("notice") Notice notice,
@JsonProperty("prefixFormatter") RemotePrefixFormatter prefixFormatter,
@JsonProperty("batchUpload") boolean batchUpload,
@JsonProperty("s3Acl") String s3Acl,
@JsonProperty("s3AclRetries") int s3AclRetries,
@JacksonInject MultipartUtils mpUtils,
@JacksonInject AWSCredentialsProvider credentialProvider); @Override String recvNotice(); @Override long checkPause(); long getFail_grantAcl(); static final String TYPE; } | @Test public void testDefaultParameters() throws Exception { String testDir = tempDir.newFolder().getAbsolutePath(); Injector injector = getInjector(); final String s3FileSink = "{\n" + " \"type\": \"" + S3FileSink.TYPE + "\",\n" + " \"localFileSink\": {\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"outputDir\": \"" + testDir + "\"\n" + " },\n" + " \"bucket\": \"s3bucket\"\n" + "}"; ObjectMapper mapper = injector.getInstance(ObjectMapper.class); Sink sink = mapper.readValue(s3FileSink, new TypeReference<Sink>(){}); sink.open(); for (Message m : new MessageSetReader(TestConnectionPool.createMessageSet(100000))) { sink.writeTo(new StringMessage(m)); } sink.close(); File[] files = getFiles(testDir); assertEquals(files.length, 0); int count = 0; while (sink.recvNotice() != null) { ++count; } assertTrue(count > 0); }
@Test public void test() throws Exception { String testDir = tempDir.newFolder().getAbsolutePath(); final String s3FileSink = "{\n" + " \"type\": \"" + S3FileSink.TYPE + "\",\n" + " \"localFileSink\": {\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"outputDir\": \"" + testDir + "\",\n" + " \"writer\": {\n" + " \"type\": \"text\"\n" + " },\n" + " \"rotationPeriod\": \"PT1m\",\n" + " \"minPercentFreeDisk\": 50,\n" + " \"notice\": {\n" + " \"type\": \"queue\"\n" + " }\n" + " },\n" + " \"bucket\": \"s3bucket\",\n" + " \"maxPartSize\": 10000,\n" + " \"concurrentUpload\":5,\n" + " \"notice\": {\n" + " \"type\": \"queue\"\n" + " },\n" + " \"prefixFormatter\": {" + " \"type\": \"DateRegionStack\",\n" + " \"date\": \"YYYYMMDD\"}\n" + "}"; Injector injector = getInjector(); ObjectMapper mapper = injector.getInstance(ObjectMapper.class); Sink sink = mapper.readValue(s3FileSink, new TypeReference<Sink>(){}); sink.open(); for (Message m : new MessageSetReader(TestConnectionPool.createMessageSet(100000))) { sink.writeTo(new StringMessage(m)); } sink.close(); File[] files = getFiles(testDir); assertEquals(files.length, 0); int count = 0; while (sink.recvNotice() != null) { ++count; } assertTrue(count > 0); }
@Test public void testTooManyFiles() throws IOException { String testDir = tempDir.newFolder().getAbsolutePath(); Injector injector = getInjector(); final String s3FileSink = "{\n" + " \"type\": \"" + S3FileSink.TYPE + "\",\n" + " \"localFileSink\": {\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"outputDir\": \"" + testDir + "\"\n" + " },\n" + " \"bucket\": \"s3bucket\"\n" + "}"; new File(testDir).mkdir(); for (int i = 0; i < 100; ++i) { createFile(testDir, i); } ObjectMapper mapper = injector.getInstance(ObjectMapper.class); Sink sink = mapper.readValue(s3FileSink, new TypeReference<Sink>(){}); sink.open(); sink.close(); File[] files = getFiles(testDir); assertEquals(files.length, 0); int count = 0; while (sink.recvNotice() != null) { ++count; } assertEquals(count, 100); }
@Test public void testUploadAll() throws IOException { String testDir = tempDir.newFolder().getAbsolutePath(); Injector injector = getInjector(); final String s3FileSink = "{\n" + " \"type\": \"" + S3FileSink.TYPE + "\",\n" + " \"localFileSink\": {\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"outputDir\": \"" + testDir + "\"\n" + " },\n" + " \"bucket\": \"s3bucket\",\n" + " \"batchUpload\":true\n" + "}"; new File(testDir).mkdir(); for (int i = 0; i < 100; ++i) { createFile(testDir, i); } ObjectMapper mapper = injector.getInstance(ObjectMapper.class); S3FileSink sink = mapper.readValue(s3FileSink, new TypeReference<Sink>(){}); sink.open(); assertEquals(sink.getNumOfPendingMessages(), 100); sink.uploadAll(testDir); int count = 0; while (sink.recvNotice() != null) { ++count; } assertEquals(count, 100); File[] files = getFiles(testDir); assertEquals(files.length, 0); assertEquals(sink.getNumOfPendingMessages(), 0); }
@Test public void testAclFailure() throws IOException, ServiceException, InterruptedException { String testDir = tempDir.newFolder().getAbsolutePath(); final String s3FileSink = "{\n" + " \"type\": \"" + S3FileSink.TYPE + "\",\n" + " \"localFileSink\": {\n" + " \"type\": \"" + LocalFileSink.TYPE + "\",\n" + " \"outputDir\": \"" + testDir + "\"\n" + " },\n" + " \"bucket\": \"s3bucket\"" + "}"; Injector injector = getInjector(); ObjectMapper mapper = injector.getInstance(ObjectMapper.class); S3FileSink sink = mapper.readValue(s3FileSink, new TypeReference<Sink>(){}); GrantAcl grantAcl = mock(GrantAcl.class); when(grantAcl.grantAcl(any(S3Object.class))).thenReturn(false); sink.open(); sink.grantAcl = grantAcl; for (Message m : new MessageSetReader(TestConnectionPool.createMessageSet(100000))) { sink.writeTo(new StringMessage(m)); } sink.close(); File[] files = getFiles(testDir); assertTrue(files.length > 0); int count = 0; while (sink.recvNotice() != null) { ++count; } assertEquals(count, 0); } |
NullValuePredicate implements ValuePredicate { @Override public boolean apply(final Object input) { return input == null; } private NullValuePredicate(); @Override boolean apply(final Object input); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final NullValuePredicate INSTANCE; } | @Test public void testNullIsAccepted() { assertTrue(NullValuePredicate.INSTANCE.apply(null)); }
@Test public void testNonNullIsRejected() { assertFalse(NullValuePredicate.INSTANCE.apply(new Object())); } |
StringValuePredicate implements ValuePredicate<String> { @Override public boolean apply(@Nullable String input) { return Objects.equal(value, input); } StringValuePredicate(@Nullable String value); @Override boolean apply(@Nullable String input); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void testValueComparison() throws Exception { Object[][] inputs = { {"abc", "abc", true}, {"", "", true}, {"AB", "A", false}, {null, null, true}, {null, "", false}, {"", null, false} }; for(Object[] input : inputs){ String value = (String)input[0]; String inputValue = (String)input[1]; boolean expected = ((Boolean)input[2]).booleanValue(); StringValuePredicate pred = new StringValuePredicate(value); assertEquals(String.format("Given value = %s, and input = %s", value, inputValue), expected, pred.apply(inputValue)); } } |
LocaleChangerDelegate { void initialize() { Locale persistedLocale = persistor.load(); if (persistedLocale != null) try { currentLocale = resolver.resolve(persistedLocale); } catch (UnsupportedLocaleException e) { persistedLocale = null; } if (persistedLocale == null) { DefaultResolvedLocalePair defaultLocalePair = resolver.resolveDefault(); currentLocale = defaultLocalePair.getResolvedLocale(); persistor.save(defaultLocalePair.getSupportedLocale()); } appLocaleChanger.change(currentLocale); } LocaleChangerDelegate(LocalePersistor persistor,
LocaleResolver resolver,
AppLocaleChanger appLocaleChanger); } | @Test public void ShouldLoadPersistedLocale_WhenInitialized() { sut.initialize(); verify(localePersistor).load(); }
@Test public void ShouldGetDefaultMatch_WhenInitialized_GivenNotPersisted() { doReturn(null).when(localePersistor).load(); sut.initialize(); verify(localeResolver).resolveDefault(); }
@Test public void ShouldPersistSupportedLocale_WhenInitialized_GivenNotPersisted() { doReturn(null).when(localePersistor).load(); doReturn(defaultLocalePair).when(localeResolver).resolveDefault(); doReturn(ANY_LOCALE).when(defaultLocalePair).getSupportedLocale(); sut.initialize(); verify(localePersistor).save(ANY_LOCALE); }
@Test public void ShouldGetMatch_WhenInitialized_GivenPersisted() throws Exception { doReturn(ANY_LOCALE).when(localePersistor).load(); sut.initialize(); verify(localeResolver).resolve(ANY_LOCALE); }
@Test public void ShouldChangeAppLocale_WhenInitialized_GivenNotPersisted() { doReturn(null).when(localePersistor).load(); sut.initialize(); verify(appLocaleChanger).change(defaultLocalePair.getResolvedLocale()); }
@Test public void ShouldChangeAppLocale_WhenInitialized_GivenPersisted() throws UnsupportedLocaleException { doReturn(ANY_LOCALE).when(localePersistor).load(); doReturn(ANY_LOCALE).when(localeResolver).resolve(ANY_LOCALE); sut.initialize(); verify(appLocaleChanger).change(ANY_LOCALE); } |
LocaleResolver { DefaultResolvedLocalePair resolveDefault() { MatchingLocales matchingPair = matchingAlgorithm.findDefaultMatch(supportedLocales, systemLocales); return matchingPair != null ? new DefaultResolvedLocalePair(matchingPair.getSupportedLocale(), matchingPair.getPreferredLocale(preference)) : new DefaultResolvedLocalePair(supportedLocales.get(0), supportedLocales.get(0)); } LocaleResolver(List<Locale> supportedLocales,
List<Locale> systemLocales,
MatchingAlgorithm matchingAlgorithm,
LocalePreference preference); } | @Test public void ShouldResolveFirstSupportedLocaleAsDefault_WhenResolveDefaultLocale_GivenNonMatchingLocales() { LocaleResolver sut = new LocaleResolver( Arrays.asList(LOCALE_ES_ES, LOCALE_IT_IT), Arrays.asList(LOCALE_EN_US, LOCALE_FR_FR), new LanguageMatchingAlgorithm(), ANY_PREFERENCE ); DefaultResolvedLocalePair defaultResolvedLocalePair = sut.resolveDefault(); Assert.assertEquals(LOCALE_ES_ES, defaultResolvedLocalePair.getResolvedLocale()); } |
LocaleResolver { Locale resolve(Locale supportedLocale) throws UnsupportedLocaleException { if (!supportedLocales.contains(supportedLocale)) throw new UnsupportedLocaleException("The Locale you are trying to load is not in the supported list provided on library initialization"); MatchingLocales matchingPair = null; if (preference.equals(LocalePreference.PreferSystemLocale)) { matchingPair = matchingAlgorithm.findMatch(supportedLocale, systemLocales); } return matchingPair != null ? matchingPair.getPreferredLocale(preference) : supportedLocale; } LocaleResolver(List<Locale> supportedLocales,
List<Locale> systemLocales,
MatchingAlgorithm matchingAlgorithm,
LocalePreference preference); } | @Test public void ShouldResolveGivenSupportedLocaleAsDefault_WhenResolveLocale_GivenNonMatchingLocales() throws UnsupportedLocaleException { LocaleResolver sut = new LocaleResolver( Arrays.asList(LOCALE_ES_ES, LOCALE_IT_IT), Arrays.asList(LOCALE_EN_US, LOCALE_FR_FR), new LanguageMatchingAlgorithm(), ANY_PREFERENCE ); Locale resolvedLocale = sut.resolve(LOCALE_IT_IT); Assert.assertEquals(LOCALE_IT_IT, resolvedLocale); }
@Test public void ShouldResolveGivenSupportedLocaleDirectly_WhenResolveLocale_PreferringSupportedLocale() throws UnsupportedLocaleException { MatchingAlgorithm matchingAlgorithm = mock(MatchingAlgorithm.class); LocaleResolver sut = new LocaleResolver( Arrays.asList(LOCALE_ES_ES, LOCALE_IT_IT), Arrays.asList(LOCALE_EN_US, LOCALE_FR_FR), matchingAlgorithm, LocalePreference.PreferSupportedLocale ); Locale resolvedLocale = sut.resolve(LOCALE_IT_IT); verify(matchingAlgorithm, never()).findMatch(LOCALE_IT_IT, Arrays.asList(LOCALE_EN_US, LOCALE_FR_FR)); Assert.assertEquals(LOCALE_IT_IT, resolvedLocale); }
@Test(expected = UnsupportedLocaleException.class) public void ShouldThrowException_WhenResolveLocale_GivenNotSupportedLocale() throws UnsupportedLocaleException { LocaleResolver sut = new LocaleResolver( Arrays.asList(LOCALE_ES_ES, LOCALE_IT_IT), Arrays.asList(LOCALE_EN_US, LOCALE_FR_FR), new LanguageMatchingAlgorithm(), ANY_PREFERENCE ); Locale unsupportedLocale = new Locale("nl", "BE"); sut.resolve(unsupportedLocale); } |
LocaleChangerDelegate { void setLocale(Locale supportedLocale) { try { currentLocale = resolver.resolve(supportedLocale); persistor.save(supportedLocale); appLocaleChanger.change(currentLocale); } catch (UnsupportedLocaleException e) { throw new IllegalArgumentException(e); } } LocaleChangerDelegate(LocalePersistor persistor,
LocaleResolver resolver,
AppLocaleChanger appLocaleChanger); } | @Test public void ShouldPersistLocaleWithSupportedLocale_WhenChanged_GivenSupportedLocale() { sut.setLocale(ANY_LOCALE); verify(localePersistor).save(ANY_LOCALE); }
@Test public void ShouldChangeAppLocaleWithAMatchingLocale_WhenChanged_GivenSupportedLocale() throws UnsupportedLocaleException { doReturn(ANY_LOCALE).when(localeResolver).resolve(ANY_LOCALE); sut.setLocale(ANY_LOCALE); verify(appLocaleChanger).change(ANY_LOCALE); }
@Test(expected = IllegalArgumentException.class) public void ShouldThrowIllegalArgumentException_WhenChanged_GivenNotSupportedLocale() throws UnsupportedLocaleException { doThrow(IllegalArgumentException.class).when(localeResolver).resolve(ANY_LOCALE); sut.setLocale(ANY_LOCALE); } |
LocaleChangerDelegate { Locale getLocale() { return persistor.load(); } LocaleChangerDelegate(LocalePersistor persistor,
LocaleResolver resolver,
AppLocaleChanger appLocaleChanger); } | @Test public void ShouldLoadPersistedLocale_WhenGetCurrentSupportedLocale() { doReturn(ANY_LOCALE).when(localePersistor).load(); Locale currentSupportedLocale = sut.getLocale(); assertEquals(ANY_LOCALE, currentSupportedLocale); } |
LibraryDBDao implements Serializable { public void destoryDB() { mDbOpenHelper = null; DataBaseOpenHelper.clearInstance(); } LibraryDBDao(Context context); void destoryDB(); boolean addBook(Book book); List<Book> queryAllBookList(); void updateBookInfo(String id, Book book); List<Book> searchBooks(String columnName, String columnValue); List<Book> searchBooks(HashMap<String, String> map); void removeBook(int id); void delAllData(); String getNotOccupiedKeyId(); static final int SEARCHTYPE_ID; } | @Test public void testSaveAndQueryAllBook() throws Exception { traverseData(); mDao.destoryDB(); } |
BatchEnvironment extends org.glassfish.rmic.tools.javac.BatchEnvironment { public static ClassPath createClassPath(String classPathString, String sysClassPathString) { Path path = new Path(); if (sysClassPathString == null) { sysClassPathString = System.getProperty("sun.boot.class.path"); } if (sysClassPathString != null) { path.addFiles(sysClassPathString); } path.expandJarClassPaths(true); path.emptyPathDefault("."); if (classPathString == null) { classPathString = System.getProperty("env.class.path"); if (classPathString == null) { classPathString = "."; } } path.addFiles(classPathString); return new ClassPath(path.toArray(new String[path.size()])); } BatchEnvironment(OutputStream out, ClassPath path, File destinationDir); static ClassPath createClassPath(String classPathString, String sysClassPathString); File getDestinationDir(); ClassPath getClassPath(); void addGeneratedFile(File file); void shutdown(); String errorString(String err,
Object arg0, Object arg1, Object arg2); void reset(); } | @Test public void createdClassPathString_usesPathSeparator() throws Exception { String systemPath = "./jdk/jre/lib/rt.jar"; String classPath = "./user.jar" + File.pathSeparator + "./user2.jar" + File.pathSeparator + "./user3.jar"; assertThat(BatchEnvironment.createClassPath(classPath, systemPath).toString().split(File.pathSeparator), arrayWithSize(4)); } |
TypeFactory { static Type createMethodType(String descriptor) { org.objectweb.asm.Type returnType = org.objectweb.asm.Type.getReturnType(descriptor); return Type.tMethod(toRmicType(returnType), toTypeArray(org.objectweb.asm.Type.getArgumentTypes(descriptor))); } } | @Test public void constructNoArgVoidMethodType() throws Exception { Type methodType = TypeFactory.createMethodType("()V"); assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); assertThat(methodType.getArgumentTypes(), emptyArray()); }
@Test public void constructByteArrayToIntType() throws Exception { Type methodType = TypeFactory.createMethodType("([B)I"); assertThat(methodType.getReturnType(), equalTo(Type.tInt)); assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tByte))); }
@Test public void constructAllNumericArgsToBooleanMethod() throws Exception { Type methodType = TypeFactory.createMethodType("(SIJFD)Z"); assertThat(methodType.getReturnType(), equalTo(Type.tBoolean)); assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tShort, Type.tInt, Type.tLong, Type.tFloat, Type.tDouble)); }
@Test public void constructAllObjectArguments() throws Exception { Type methodType = TypeFactory.createMethodType("(Ljava/lang/String;Lorg/glassfish/rmic/classes/nestedClasses/TwoLevelNested$Level1;)V"); assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tString, Type.tClass(Identifier.lookup(TwoLevelNested.Level1.class.getName())))); }
@Test public void constructObjectArrayArgument() throws Exception { Type methodType = TypeFactory.createMethodType("([Ljava/lang/Object;)V"); assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tObject))); }
@Test public void constructCharArrayArgument() throws Exception { Type methodType = TypeFactory.createMethodType("([C)V"); assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tChar))); } |
TypeFactory { static Type createType(String descriptor) { return toRmicType(org.objectweb.asm.Type.getType(descriptor)); } } | @Test public void constructMultiDimensionalArrayType() throws Exception { assertThat(TypeFactory.createType("[[I"), equalTo(Type.tArray(Type.tArray(Type.tInt)))); } |
Main implements org.glassfish.rmic.Constants { boolean displayErrors(BatchEnvironment env) { List<String> summary = new ArrayList<>(); if (env.nerrors > 0) summary.add(getErrorSummary(env)); if (env.nwarnings > 0) summary.add(getWarningSummary(env)); if (!summary.isEmpty()) output(String.join(", ", summary)); return env.nerrors == 0; } Main(OutputStream out, String program); void output(String msg); void error(String msg); void error(String msg, String arg1); void error(String msg, String arg1, String arg2); void usage(); synchronized boolean compile(String argv[]); File getDestinationDir(); boolean parseArgs(String... argv); BatchEnvironment getEnv(); void compileAllClasses(BatchEnvironment env); @SuppressWarnings({"fallthrough", "deprecation"}) boolean compileClass(ClassDeclaration c,
ByteArrayOutputStream buf,
BatchEnvironment env); static void main(String argv[]); static String getString(String key); static String getText(String key); static String getText(String key, int num); static String getText(String key, String arg0); static String getText(String key, String arg0, String arg1); static String getText(String key,
String arg0, String arg1, String arg2); } | @Test public void whenNoErrorsOrWarnings_displayErrorsReturnsTrue() throws Exception { assertThat(main.displayErrors(environment), is(true)); }
@Test public void whenNoErrorsOrWarnings_outputIsEmpty() throws Exception { main.displayErrors(environment); assertThat(getOutput(), isEmptyString()); }
@Test public void afterOneError_outputReportsOneError() throws Exception { reportError(); main.displayErrors(environment); assertThat(getOutput(), containsString("1 error")); }
@Test public void afterThreeErrors_outputReportsNumberOfErrors() throws Exception { reportError(); reportError(); reportError(); main.displayErrors(environment); assertThat(getOutput(), containsString("3 errors")); }
@Test public void afterOneWarning_outputReportsOneWarning() throws Exception { reportWarning(); main.displayErrors(environment); assertThat(getOutput(), containsString("1 warning")); }
@Test public void afterThreeWarningss_outputReportsNumberOfErrors() throws Exception { reportWarning(); reportWarning(); reportWarning(); main.displayErrors(environment); assertThat(getOutput(), containsString("3 warnings")); }
@Test public void afterOneErrorAndTwoWarnings_outputReportsNumbersOfBoth() throws Exception { reportError(); reportWarning(); reportWarning(); main.displayErrors(environment); assertThat(getOutput(), containsString("1 error, 2 warnings")); }
@Test public void afterTwoErrorsAndOneWarnings_outputReportsNumbersOfBoth() throws Exception { reportError(); reportError(); reportWarning(); main.displayErrors(environment); assertThat(getOutput(), containsString("2 errors, 1 warning")); } |
BatchEnvironment extends Environment implements ErrorConsumer { static ClassDefinitionFactory createClassDefinitionFactory() { try { return useBinaryClassFactory() ? new BinaryClassFactory() : new AsmClassFactory(); } catch (NoClassDefFoundError e) { if (!mayUseBinaryClassFactory()) throw new BatchEnvironmentError("RMIC is unable to parse class files at this JDK level without an appropriate version of ASM in its class path"); return new BinaryClassFactory(); } } BatchEnvironment(OutputStream out,
ClassPath binaryPath); BatchEnvironment(OutputStream out,
ClassPath binaryPath,
ErrorConsumer errorConsumer); int getFlags(); short getMajorVersion(); short getMinorVersion(); File getcovFile(); Enumeration<ClassDeclaration> getClasses(); Iterable<ClassDeclaration> getGeneratedClasses(); boolean isExemptPackage(Identifier id); ClassDeclaration getClassDeclaration(Identifier nm); ClassDeclaration getClassDeclaration(Type t); boolean classExists(Identifier nm); Package getPackage(Identifier pkg); void parseFile(ClassFile file); void loadDefinition(ClassDeclaration c); ClassDefinition makeClassDefinition(Environment toplevelEnv,
long where,
IdentifierToken name,
String doc, int modifiers,
IdentifierToken superClass,
IdentifierToken interfaces[],
ClassDefinition outerClass); @SuppressWarnings({"rawtypes","unchecked"}) MemberDefinition makeMemberDefinition(Environment origEnv, long where,
ClassDefinition clazz,
String doc, int modifiers,
Type type, Identifier name,
IdentifierToken argNames[],
IdentifierToken expIds[],
Object value); void shutdown(); String errorString(String err, Object arg1, Object arg2, Object arg3); void pushError(String errorFileName, int line, String message,
String referenceText, String referenceTextPointer); void flushErrors(); void error(Object source, long where, String err, Object arg1, Object arg2, Object arg3); void output(String msg); public int flags; public short majorVersion; public short minorVersion; public int nerrors; public int nwarnings; } | @Test public void whenPropertyNotSet_chooseAsmParser() throws Exception { ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(AsmClassFactory.class)); }
@Test public void whenAsmClassesMissingOnJdk8_chooseBinaryParser() throws Exception { simulateAsmClassesMissing(); simulateJdkVersion("1.8"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(BinaryClassFactory.class)); }
@Test(expected = BatchEnvironmentError.class) public void whenAsmClassesMissingOnJdk10_reportError() throws Exception { simulateAsmClassesMissing(); simulateJdkVersion("10"); BatchEnvironment.createClassDefinitionFactory(); }
@Test public void whenLegacyParserRequestedOnJdk8_chooseBinaryParser() throws Exception { preferLegacyParser(); simulateJdkVersion("1.8"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(BinaryClassFactory.class)); }
@Test public void whenLegacyParserRequestedOnJdk9_chooseBinaryParser() throws Exception { preferLegacyParser(); simulateJdkVersion("9"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(BinaryClassFactory.class)); }
@Test public void whenLegacyParserRequestedOnJdk10_chooseAsmParser() throws Exception { preferLegacyParser(); simulateJdkVersion("10"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(AsmClassFactory.class)); }
@Test public void whenLegacyParserRequestedOnJdk10EarlyAccess_chooseAsmParser() throws Exception { preferLegacyParser(); simulateJdkVersion("10-ea"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(AsmClassFactory.class)); }
@Test public void whenLegacyParserRequestedOnJdk11_chooseAsmParser() throws Exception { preferLegacyParser(); simulateJdkVersion("11"); ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(AsmClassFactory.class)); } |
ClientRequestDispatcherImpl implements
ClientRequestDispatcher { @Subcontract public CDRInputObject marshalingComplete(java.lang.Object self, CDROutputObject outputObject) throws ApplicationException, org.omg.CORBA.portable.RemarshalException { MessageMediator messageMediator = outputObject.getMessageMediator(); ORB orb = messageMediator.getBroker(); operationAndId(messageMediator.getOperationName(), messageMediator.getRequestId() ); try { exit_clientEncoding(); enter_clientTransportAndWait(); CDRInputObject inputObject = null ; try { inputObject = marshalingComplete1(orb, messageMediator); } finally { exit_clientTransportAndWait(); } return processResponse(orb, messageMediator, inputObject); } finally { enter_clientDecoding() ; } } @Subcontract CDROutputObject beginRequest(Object self, String opName,
boolean isOneWay, ContactInfo contactInfo); @Subcontract CDRInputObject marshalingComplete(java.lang.Object self,
CDROutputObject outputObject); @Subcontract CDRInputObject marshalingComplete1(
ORB orb, MessageMediator messageMediator); @Subcontract void endRequest(ORB orb, Object self, CDRInputObject inputObject); } | @Test(expected = RemarshalException.class) public void whenPIHandleReturnsRemarshalException_throwIt() throws Exception { orb.setPiEndingPointException(new RemarshalException()); impl.marshalingComplete(null, outputObject); } |
StubInvocationHandlerImpl implements LinkedInvocationHandler { public Object invoke( Object proxy, final Method method, Object[] args ) throws Throwable { Delegate delegate = null ; try { delegate = StubAdapter.getDelegate( stub ) ; } catch (SystemException ex) { throw Util.getInstance().mapSystemException(ex) ; } org.omg.CORBA.ORB delORB = delegate.orb( stub ) ; if (delORB instanceof ORB) { ORB orb = (ORB)delORB ; InvocationInterceptor interceptor = orb.getInvocationInterceptor() ; try { interceptor.preInvoke() ; } catch (Exception exc) { } try { return privateInvoke( delegate, proxy, method, args ) ; } finally { try { interceptor.postInvoke() ; } catch (Exception exc) { } } } else { return privateInvoke( delegate, proxy, method, args ) ; } } StubInvocationHandlerImpl( PresentationManager pm,
PresentationManager.ClassData classData, org.omg.CORBA.Object stub ); void setProxy( Proxy self ); Proxy getProxy(); Object invoke( Object proxy, final Method method,
Object[] args ); } | @Test public void whenColocatedCallThrowsException_exceptionHasStackTrace() throws Throwable { try { handler.invoke(calledObject, throwExceptionMethod, new Object[0]); } catch (TestException exception) { assertThat(exception.getStackTrace(), not(emptyArray())); } } |
JNDIStateFactoryImpl implements StateFactory { public Object getStateToBind(Object orig, Name name, Context ctx, Hashtable<?,?> env) throws NamingException { if (orig instanceof org.omg.CORBA.Object) { return orig; } if (!(orig instanceof Remote)) { return null; } ORB orb = getORB( ctx ) ; if (orb == null) { return null ; } Remote stub; try { stub = PortableRemoteObject.toStub( (Remote)orig ) ; } catch (Exception exc) { Exceptions.self.noStub( exc ) ; return null ; } if (StubAdapter.isStub( stub )) { try { StubAdapter.connect( stub, orb ) ; } catch (Exception exc) { Exceptions.self.couldNotConnect( exc ) ; if (!(exc instanceof java.rmi.RemoteException)) { return null ; } } } return stub ; } @SuppressWarnings("WeakerAccess") JNDIStateFactoryImpl(); Object getStateToBind(Object orig, Name name, Context ctx,
Hashtable<?,?> env); } | @Test public void whenObjectIsCorbaObject_returnIt() throws Exception { Object testObject = createStrictStub(org.omg.CORBA.Object.class); assertThat(impl.getStateToBind(testObject, null, null, env), sameInstance(testObject)); }
@Test public void whenObjectIsNotRemote_returnNull() throws Exception { assertThat(impl.getStateToBind(new Object(), null, null, env), nullValue()); }
@Test public void whenCannotGetOrbFromContext_returnNull() throws Exception { assertThat(impl.getStateToBind(remote, null, createStrictStub(Context.class), env), nullValue()); }
@Test public void whenObjectIsNotAStub_returnNull() throws Exception { installDelegate(createStrictStub(NoStubDelegate.class)); assertThat(impl.getStateToBind(remote, null, context, env), nullValue()); }
@Test public void whenObjectIsAStub_returnIt() throws Exception { installDelegateForStub(corbaStub); Object state = impl.getStateToBind(remote, null, context, env); assertThat(state, sameInstance(corbaStub)); }
@Test public void whenObjectIsAStub_connectIt() throws Exception { installDelegateForStub(corbaStub); impl.getStateToBind(remote, null, context, env); assertThat(corbaStub.connected, is(true)); } |
SocketChannelReader { public ByteBuffer read(SocketChannel channel, ByteBuffer previouslyReadData, int minNeeded) throws IOException { ByteBuffer byteBuffer = prepareToAppendTo(previouslyReadData); int numBytesRead = channel.read(byteBuffer); if (numBytesRead < 0) { throw new EOFException("End of input detected"); } else if (numBytesRead == 0) { byteBuffer.flip(); return null; } while (numBytesRead > 0 && byteBuffer.position() < minNeeded) { if (haveFilledBuffer(byteBuffer)) byteBuffer = expandBuffer(byteBuffer); numBytesRead = channel.read(byteBuffer); } return byteBuffer; } SocketChannelReader(ORB orb); ByteBuffer read(SocketChannel channel, ByteBuffer previouslyReadData, int minNeeded); } | @Test public void whenCurrentBufferNull_allocateBufferAndRead() throws IOException { enqueData(DATA_TO_BE_READ); ByteBuffer buffer = reader.read(getSocketChannel(), null, 0); assertBufferContents(buffer, DATA_TO_BE_READ); }
@Test public void whenCurrentBufferHasPartialData_readToAppendData() throws IOException { ByteBuffer oldBuffer = ByteBuffer.allocate(100); populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 0); assertBufferContents(buffer, DATA_TO_BE_READ); }
@Test public void whenCurrentBufferIsFull_readToAppendData() throws IOException { ByteBuffer oldBuffer = ByteBuffer.allocate(3); populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 0); assertBufferContents(buffer, DATA_TO_BE_READ); }
@Test public void whenCurrentBufferTooSmallForIncomingData_reallocateAndAppend() throws IOException { ByteBuffer oldBuffer = ByteBuffer.allocate(5); populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, DATA_TO_BE_READ.length); assertBufferContents(buffer, DATA_TO_BE_READ); }
@Test public void whenMoreDataAvailableThanNeeded_ignoreIt() throws IOException { ByteBuffer oldBuffer = ByteBuffer.allocate(10); oldBuffer.flip(); enqueData(DATA_TO_BE_READ); getSocketChannel().setNumBytesToRead(3, 3); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 2); assertBufferContents(buffer, getSubarray(DATA_TO_BE_READ, 0, 3)); }
@Test(expected = EOFException.class) public void whenEOFDetectedThrowException() throws IOException { getSocketChannel().setEndOfInput(); ByteBuffer oldBuffer = ByteBuffer.allocate(5); reader.read(getSocketChannel(), oldBuffer, 0); }
@Test public void whenNoDataRemains_returnNull() throws IOException { ByteBuffer oldBuffer = ByteBuffer.allocate(10); populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, DATA_TO_BE_READ.length); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 10); assertNull(buffer); assertPopulatedBufferContents(oldBuffer, DATA_TO_BE_READ); }
@Test public void whenAtCapacityAndNoDataRemains_returnNullAndPreserveOldBuffer() throws IOException { ByteBuffer oldBuffer = ByteBuffer.wrap(DATA_TO_BE_READ); ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 10); assertNull(buffer); assertPopulatedBufferContents(oldBuffer, DATA_TO_BE_READ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.