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...
@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(":")); a...
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 ...
@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...
@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.ge...
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);...
@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 + "' configura...
@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) { } ...
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 ps...
@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(); decorato...
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 == ...
@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...
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"); } } ...
@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 RemoteFil...
@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, subjec...
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(); Stri...
@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); assertN...
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...
@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 RemoteFi...
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 ...
@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); a...
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 setPatt...
@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(wildcardMa...
@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); ...
@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...
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)) {...
@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( ...
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 StringBu...
@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 getProxyHo...
@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",...
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++, ...
@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(...
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.p...
@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 ...
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()...
@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.eval...
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> consta...
@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.evaluat...
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 addE...
@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 Dec...
@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 De...
@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 De...
@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...
@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(...
@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(e...
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 ...
@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( tm...
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"; SasToke...
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...
@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 D...
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 Configurat...
@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.setSource...
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 (Stri...
@Test public void basic() throws IOException, ConfigurationException, TransformException { String cfgData = "{ \"field\" : \"number\", \"format\" : \"#,###\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFr...
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 (Strin...
@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(); workingFr...
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 ConfigurationExcep...
@Test public void basic() throws IOException, ConfigurationException, TransformException, DataFrameException { String cfgData = "{ \"field\" : \"TotalCost\", \"subtrahend\" : \"10\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = n...
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 (f...
@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(CheckFieldMe...
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) { th...
@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")); assertFals...
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, fina...
@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, f...
@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.e...
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, fin...
@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(CheckFieldMe...
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...
@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(...
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(...
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 Tran...
@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 shou...
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, targetCookie...
@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(ed...
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 cookieRem...
@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 con...
@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 p...
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>...
@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...
@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(); voi...
@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 AlwaysFalseMessageFilt...
@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 Me...
@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 Messa...
@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); st...
@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); ...
@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)...
@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 i...
@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.DUMM...
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("...
@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(...
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 equa...
@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() {...
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 I...
@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(); @Over...
@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 Rout...
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 conv...
@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() throw...
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, Inpu...
@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...
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...
@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" +...
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 : batchTim...
@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 { } @...
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); stat...
@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,...
@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 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("output...
@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...
@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 =...
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.getI...
@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("201...
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...
@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 JsonPro...
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, Va...
@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)...
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") St...
@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<St...
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();...
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...
@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) ...
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().setSoLinge...
@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 pingFailTe...
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 {...
@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.ch...
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 : liste...
@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...
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 = js...
@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()...
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,...
S3FileSink extends RemoteFileSink { @Override public String recvNotice() { return notice.recv(); } @JsonCreator S3FileSink( @JsonProperty("localFileSink") LocalFileSink localFileSink, @JsonProperty("bucket") String bucket, @JsonProperty("s3Endpoint") String s3Endpoint, @...
@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" + " \"outputD...
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 Nu...
@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 ...
@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 = (...
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 = res...
@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 Sh...
LocaleResolver { DefaultResolvedLocalePair resolveDefault() { MatchingLocales matchingPair = matchingAlgorithm.findDefaultMatch(supportedLocales, systemLocales); return matchingPair != null ? new DefaultResolvedLocalePair(matchingPair.getSupportedLocale(), matchingPair.getPreferredLocale(preference)) : new DefaultResol...
@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 de...
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 ...
@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 ); L...
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 per...
@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...
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, St...
@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 != nu...
@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....
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 metho...
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 en...
@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 after...
BatchEnvironment extends Environment implements ErrorConsumer { static ClassDefinitionFactory createClassDefinitionFactory() { try { return useBinaryClassFactory() ? new BinaryClassFactory() : new AsmClassFactory(); } catch (NoClassDefFoundError e) { if (!mayUseBinaryClassFactory()) throw new BatchEnvironmentError("RMI...
@Test public void whenPropertyNotSet_chooseAsmParser() throws Exception { ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); assertThat(factory, instanceOf(AsmClassFactory.class)); } @Test public void whenAsmClassesMissingOnJdk8_chooseBinaryParser() throws Exception { simulateAsmClassesMi...
ClientRequestDispatcherImpl implements ClientRequestDispatcher { @Subcontract public CDRInputObject marshalingComplete(java.lang.Object self, CDROutputObject outputObject) throws ApplicationException, org.omg.CORBA.portable.RemarshalException { MessageMediator messageMediator = outputObject.getMessageMediator()...
@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....
@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 nul...
@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.getS...
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"); } el...
@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 { ByteBu...