method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Preconditions { public static void checkEmptyString(String string, String errorMsg) { check(hasText(string), errorMsg); } static void checkNotNull(Object object, String errorMsg); static void checkEmptyString(String string, String errorMsg); static boolean hasText(String str); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForNullStrings() { Preconditions.checkEmptyString(null, ERROR_MSG); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForEmptyStrings() { Preconditions.checkEmptyString("", ERROR_MSG); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForSpacesOnlyStrings() { Preconditions.checkEmptyString(" ", ERROR_MSG); } |
### Question:
FitBitJsonTokenExtractor extends OAuth2AccessTokenJsonExtractor { @Override public void generateError(String rawResponse) throws IOException { final JsonNode errorNode = OAuth2AccessTokenJsonExtractor.OBJECT_MAPPER.readTree(rawResponse) .get("errors").get(0); OAuth2Error errorCode; try { errorCode = OAuth2Error.parseFrom(extractRequiredParameter(errorNode, "errorType", rawResponse).asText()); } catch (IllegalArgumentException iaE) { errorCode = null; } throw new OAuth2AccessTokenErrorResponse(errorCode, errorNode.get("message").asText(), null, rawResponse); } protected FitBitJsonTokenExtractor(); static FitBitJsonTokenExtractor instance(); @Override void generateError(String rawResponse); }### Answer:
@Test public void testErrorExtraction() throws IOException { final FitBitJsonTokenExtractor extractor = new FitBitJsonTokenExtractor(); final OAuth2AccessTokenErrorResponse thrown = assertThrows(OAuth2AccessTokenErrorResponse.class, new ThrowingRunnable() { @Override public void run() throws Throwable { extractor.generateError(ERROR_JSON); } }); assertSame(OAuth2Error.INVALID_GRANT, thrown.getError()); assertEquals(ERROR_DESCRIPTION, thrown.getErrorDescription()); } |
### Question:
OAuthEncoder { public static String encode(String plain) { Preconditions.checkNotNull(plain, "Cannot encode null object"); String encoded; try { encoded = URLEncoder.encode(plain, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while encoding string: " + CHARSET, uee); } for (Map.Entry<String, String> rule : ENCODING_RULES.entrySet()) { encoded = applyRule(encoded, rule.getKey(), rule.getValue()); } return encoded; } static String encode(String plain); static String decode(String encoded); }### Answer:
@Test public void shouldPercentEncodeString() { final String plain = "this is a test &^"; final String encoded = "this%20is%20a%20test%20%26%5E"; assertEquals(encoded, OAuthEncoder.encode(plain)); }
@Test public void shouldNotPercentEncodeReservedCharacters() { final String plain = "abcde123456-._~"; final String encoded = plain; assertEquals(encoded, OAuthEncoder.encode(plain)); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfStringToEncodeIsNull() { OAuthEncoder.encode(null); }
@Test public void shouldPercentEncodeCorrectlyTwitterCodingExamples() { final String[] sources = {"Ladies + Gentlemen", "An encoded string!", "Dogs, Cats & Mice"}; final String[] encoded = {"Ladies%20%2B%20Gentlemen", "An%20encoded%20string%21", "Dogs%2C%20Cats%20%26%20Mice"}; for (int i = 0; i < sources.length; i++) { assertEquals(encoded[i], OAuthEncoder.encode(sources[i])); } } |
### Question:
OAuthEncoder { public static String decode(String encoded) { Preconditions.checkNotNull(encoded, "Cannot decode null object"); try { return URLDecoder.decode(encoded, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while decoding string: " + CHARSET, uee); } } static String encode(String plain); static String decode(String encoded); }### Answer:
@Test public void shouldFormURLDecodeString() { final String encoded = "this+is+a+test+%26%5E"; final String plain = "this is a test &^"; assertEquals(plain, OAuthEncoder.decode(encoded)); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfStringToDecodeIsNull() { OAuthEncoder.decode(null); } |
### Question:
StreamUtils { public static String getStreamContents(InputStream is) throws IOException { Preconditions.checkNotNull(is, "Cannot get String from a null object"); final char[] buffer = new char[0x10000]; final StringBuilder out = new StringBuilder(); try (Reader in = new InputStreamReader(is, "UTF-8")) { int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); } return out.toString(); } static String getStreamContents(InputStream is); static String getGzipStreamContents(InputStream is); }### Answer:
@Test public void shouldCorrectlyDecodeAStream() throws IOException { final String value = "expected"; final InputStream is = new ByteArrayInputStream(value.getBytes()); final String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); }
@Test(expected = IllegalArgumentException.class) public void shouldFailForNullParameter() throws IOException { StreamUtils.getStreamContents(null); fail("Must throw exception before getting here"); }
@Test(expected = IOException.class) public void shouldFailWithBrokenStream() throws IOException { StreamUtils.getStreamContents(ALLWAYS_ERROR_INPUT_STREAM); fail("Must throw exception before getting here"); } |
### Question:
OAuthAsyncCompletionHandler implements Callback { @Override public void onFailure(Call call, IOException exception) { try { okHttpFuture.setException(exception); if (callback != null) { callback.onThrowable(exception); } } finally { okHttpFuture.finish(); } } OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter,
OkHttpFuture<T> okHttpFuture); @Override void onFailure(Call call, IOException exception); @Override void onResponse(Call call, okhttp3.Response okHttpResponse); }### Answer:
@Test public void shouldReleaseLatchOnFailure() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER, future); call.enqueue(handler); handler.onFailure(call, new IOException()); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callback.getThrowable() instanceof IOException); try { future.get(); fail(); } catch (ExecutionException expected) { } } |
### Question:
HMACSha1SignatureService implements SignatureService { @Override public String getSignatureMethod() { return METHOD; } @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); }### Answer:
@Test public void shouldReturnSignatureMethodString() { final String expected = "HMAC-SHA1"; assertEquals(expected, service.getSignatureMethod()); } |
### Question:
CSRFToken implements Serializable { public String getParameterName() { return parameterName; } CSRFToken(String token); CSRFToken(String headerName, String parameterName, String token); String getHeaderName(); String getParameterName(); String getToken(); }### Answer:
@Test public void testPOSTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(post("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); }
@Test public void testPUTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(put("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); }
@Test public void testDELETERequestsWithWrongToken() throws Exception { this.mockMvc.perform(delete("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); } |
### Question:
FileSystemLogRepository implements ExecutionLogRepository { @Override public void update(ExecutionLog log) { store(log, readJson(logFileFor(log.getTaskName(), log.getId())).map(obj -> obj.getAsJsonPrimitive("previous")).map( JsonPrimitive::getAsString)); } FileSystemLogRepository(String basePath, int dispersionFactor); FileSystemLogRepository(int dispersionFactor); void setBasePath(String basePath); @Override void update(ExecutionLog log); @Override void newExecution(ExecutionLog log); @Override void appendTaskLog(ExecutionLog log, String text); @Override void storeFile(ExecutionLog log, String fileName, byte[] contents, boolean append); @Override Stream<ExecutionLog> latest(); @Override Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max); @Override Optional<String> getTaskLog(String taskName, String id); @Override Optional<byte[]> getFile(String taskName, String id, String fileName); @Override Optional<ExecutionLog> getLog(String taskName, String id); }### Answer:
@Test public void testUpdate() { ExecutionLog original = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(original); assertEquals(original, repository.getLog(original.getTaskName(), original.getId()).get()); ExecutionLog log = original.withSuccess(); repository.update(log); assertEquals(log, repository.getLog(original.getTaskName(), original.getId()).get()); } |
### Question:
ExecutionLog { public static ExecutionLog newExecutionFor(String taskName) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostName(), Optional.empty(), Optional.empty()); } protected ExecutionLog(JsonObject json); private ExecutionLog(String id, DateTime start, Optional<DateTime> end, TaskState state, String taskName,
Optional<String> stackTrace, Set<String> files, String hostname, Optional<String> code, Optional<String> user); static ExecutionLog newExecutionFor(String taskName); static ExecutionLog newCustomExecution(String taskName, String code, String user); String getId(); DateTime getStart(); Optional<DateTime> getEnd(); TaskState getState(); String getTaskName(); Optional<String> getStackTrace(); Set<String> getFiles(); String getHostname(); Optional<String> getCode(); Optional<String> getUser(); ExecutionLog withSuccess(); ExecutionLog withError(Throwable t); ExecutionLog withFile(String filename); JsonObject json(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test(expected = NullPointerException.class) public void testNullTaskName() { ExecutionLog.newExecutionFor(null); } |
### Question:
ExecutionLog { public static ExecutionLog newCustomExecution(String taskName, String code, String user) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostName(), Optional.of(code), Optional.of(user)); } protected ExecutionLog(JsonObject json); private ExecutionLog(String id, DateTime start, Optional<DateTime> end, TaskState state, String taskName,
Optional<String> stackTrace, Set<String> files, String hostname, Optional<String> code, Optional<String> user); static ExecutionLog newExecutionFor(String taskName); static ExecutionLog newCustomExecution(String taskName, String code, String user); String getId(); DateTime getStart(); Optional<DateTime> getEnd(); TaskState getState(); String getTaskName(); Optional<String> getStackTrace(); Set<String> getFiles(); String getHostname(); Optional<String> getCode(); Optional<String> getUser(); ExecutionLog withSuccess(); ExecutionLog withError(Throwable t); ExecutionLog withFile(String filename); JsonObject json(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test(expected = NullPointerException.class) public void testNullTaskNameOnCustomTask() { ExecutionLog.newCustomExecution(null, "code", "myself"); }
@Test(expected = NullPointerException.class) public void testNullCode() { ExecutionLog.newCustomExecution(TASK_NAME, null, "myself"); }
@Test(expected = NullPointerException.class) public void testNullTaskNamesDontWork() { ExecutionLog.newCustomExecution(TASK_NAME, "code", null); } |
### Question:
GuitarString { public void tic() { double newAveragedDouble = DECAY * (buffer.dequeue() + buffer.peek()) / 2; buffer.enqueue(newAveragedDouble); } GuitarString(double frequency); void pluck(); void tic(); double sample(); }### Answer:
@Test public void testTic() { GuitarString s = new GuitarString(11025); s.pluck(); double s1 = s.sample(); s.tic(); double s2 = s.sample(); s.tic(); double s3 = s.sample(); s.tic(); double s4 = s.sample(); s.tic(); double s5 = s.sample(); double expected = 0.996 * 0.5 * (s1 + s2); assertEquals(expected, s5, 0.001); } |
### Question:
Plip extends Creature { public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> emptySpaces = getNeighborsOfType(neighbors, "empty"); List<Direction> cloruses = getNeighborsOfType(neighbors, "clorus"); if (emptySpaces.isEmpty()) { return new Action(Action.ActionType.STAY); } if (energy > 1) { Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.REPLICATE, moveDir); } if (!cloruses.isEmpty()) { if (HugLifeUtils.random() < 0.5) { Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.MOVE, moveDir); } } return new Action(Action.ActionType.STAY); } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); }### Answer:
@Test public void testChoose() { Plip p = new Plip(1.2); HashMap<Direction, Occupant> surrounded = new HashMap<Direction, Occupant>(); surrounded.put(Direction.TOP, new Impassible()); surrounded.put(Direction.BOTTOM, new Impassible()); surrounded.put(Direction.LEFT, new Impassible()); surrounded.put(Direction.RIGHT, new Impassible()); Action actual = p.chooseAction(surrounded); Action expected = new Action(Action.ActionType.STAY); assertEquals(expected, actual); } |
### Question:
Board implements WorldState { public int tileAt(int i, int j) { if (i < 0 || i >= N || j < 0 || j >= N) { throw new IndexOutOfBoundsException("Invalid row and/or column"); } return tiles[i][j]; } Board(int[][] tiles); int tileAt(int i, int j); int size(); int hamming(); int manhattan(); int hashCode(); boolean equals(Object y); @Override int estimatedDistanceToGoal(); @Override Iterable<WorldState> neighbors(); @Override boolean isGoal(); String toString(); }### Answer:
@Test public void verifyImmutability() { int r = 2; int c = 2; int[][] x = new int[r][c]; int cnt = 0; for (int i = 0; i < r; i += 1) { for (int j = 0; j < c; j += 1) { x[i][j] = cnt; cnt += 1; } } Board b = new Board(x); assertEquals("Your Board class is not being initialized with the right values.", 0, b.tileAt(0, 0)); assertEquals("Your Board class is not being initialized with the right values.", 1, b.tileAt(0, 1)); assertEquals("Your Board class is not being initialized with the right values.", 2, b.tileAt(1, 0)); assertEquals("Your Board class is not being initialized with the right values.", 3, b.tileAt(1, 1)); x[1][1] = 1000; assertEquals("Your Board class is mutable and you should be making a copy of the values in the passed tiles array. Please see the FAQ!", 3, b.tileAt(1, 1)); } |
### Question:
IntList { public static IntList list(Integer... args) { IntList result, p; if (args.length > 0) { result = new IntList(args[0], null); } else { return null; } int k; for (k = 1, p = result; k < args.length; k += 1, p = p.rest) { p.rest = new IntList(args[k], null); } return result; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer:
@Test public void testList() { IntList one = new IntList(1, null); IntList twoOne = new IntList(2, one); IntList threeTwoOne = new IntList(3, twoOne); IntList x = IntList.list(3, 2, 1); assertEquals(threeTwoOne, x); } |
### Question:
IntList { public static void dSquareList(IntList L) { while (L != null) { L.first = L.first * L.first; L = L.rest; } } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer:
@Test public void testdSquareList() { IntList L = IntList.list(1, 2, 3); IntList.dSquareList(L); assertEquals(IntList.list(1, 4, 9), L); } |
### Question:
IntList { public static IntList squareListRecursive(IntList L) { if (L == null) { return null; } return new IntList(L.first * L.first, squareListRecursive(L.rest)); } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer:
@Test public void testSquareListRecursive() { IntList L = IntList.list(1, 2, 3); IntList res = IntList.squareListRecursive(L); assertEquals(IntList.list(1, 2, 3), L); assertEquals(IntList.list(1, 4, 9), res); } |
### Question:
IntList { public static IntList dcatenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer:
@Test public void testDcatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.dcatenate(A, B)); assertEquals(IntList.list(1, 2, 3, 4, 5, 6), A); } |
### Question:
IntList { public static IntList catenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer:
@Test public void testCatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.catenate(A, B)); assertEquals(IntList.list(1, 2, 3), A); } |
### Question:
Boggle { public static String answerString(List<String> answers, int numberOfAnswers) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < answers.size() && i < numberOfAnswers; i++) { sb.append(answers.get(i)).append('\n'); } sb.setLength(sb.length() - 1); return sb.toString(); } static void main(String[] args); static String answerString(List<String> answers, int numberOfAnswers); }### Answer:
@Test public void solveBoard() { List<String> boardLines = null; List<String> dictionaryWords = null; try { boardLines = Files.readAllLines(Paths.get("testBoggle")); dictionaryWords = Files.readAllLines(Paths.get("words")); } catch (IOException e) { e.printStackTrace(); } Board board = new Board(boardLines, dictionaryWords); String expected = "thumbtacks\n" + "thumbtack\n" + "setbacks\n" + "setback\n" + "ascent\n" + "humane\n" + "smacks"; assertEquals(expected, Boggle.answerString(board.getAnswers(), 7)); try { boardLines = Files.readAllLines(Paths.get("testBoggle2")); dictionaryWords = Files.readAllLines(Paths.get("testDict")); } catch (IOException e) { e.printStackTrace(); } board = new Board(boardLines, dictionaryWords); expected = "aaaaa\n" + "aaaa"; assertEquals(expected, Boggle.answerString(board.getAnswers(), 20)); } |
### Question:
Arithmetic { public static int product(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); }### Answer:
@Test public void testProduct() { assertEquals(30, Arithmetic.product(5, 6)); assertEquals(-30, Arithmetic.product(5, -6)); assertEquals(0, Arithmetic.product(0, -6)); } |
### Question:
Arithmetic { public static int sum(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); }### Answer:
@Test public void testSum() { assertEquals(11, Arithmetic.sum(5, 6)); assertEquals(-1, Arithmetic.sum(5, -6)); assertEquals(-6, Arithmetic.sum(0, -6)); assertEquals(0, Arithmetic.sum(6, -6)); } |
### Question:
Trie { public List<String> getWordsContainingPrefix(String prefix) { LinkedList<String> words = new LinkedList<>(); Node pointer = root; for (int i = 0; i < prefix.length(); i++) { char currentChar = prefix.charAt(i); if (!pointer.children.containsKey(currentChar)) { return words; } pointer = pointer.children.get(currentChar); } Node prefixEndNode = pointer; List<Node> endNodes = getAllEndNodesContainingPrefix(prefixEndNode); for (Node node : endNodes) { StringBuilder sb = new StringBuilder(); pointer = node; while (pointer != prefixEndNode) { sb.append(pointer.character); pointer = pointer.parent; } words.add(prefix + sb.reverse().toString()); } return words; } void add(String word); boolean containsWord(String word); List<String> getWordsContainingPrefix(String prefix); }### Answer:
@Test public void getWordsContainingPrefix() { Trie trie = new Trie(); trie.add("app"); trie.add("appearance"); trie.add("apple"); trie.add("appliance"); trie.add("application"); trie.add("montclair"); trie.add("mountain"); List<String> wordsContainingPrefix = trie.getWordsContainingPrefix("foster"); assertEquals(0, wordsContainingPrefix.size()); wordsContainingPrefix = trie.getWordsContainingPrefix("mont"); List<String> expected = Arrays.asList("montclair"); assertEquals(expected, wordsContainingPrefix); wordsContainingPrefix = trie.getWordsContainingPrefix("app"); expected = Arrays.asList("app", "application", "appliance", "apple", "appearance"); assertEquals(expected, wordsContainingPrefix); } |
### Question:
Dog { public String noise() { if (size < 10) { return "yip"; } return "bark"; } Dog(int s); String noise(); }### Answer:
@Test public void testSmall() { Dog d = new Dog(3); assertEquals("yip", d.noise()); }
@Test public void testLarge() { Dog d = new Dog(20); assertEquals("bark", d.noise()); } |
### Question:
SimpleOomage implements Oomage { @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } if (this == o || this.hashCode() == o.hashCode()) { return true; } return false; } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); @Override void draw(double x, double y, double scalingFactor); static SimpleOomage randomSimpleOomage(); static void main(String[] args); String toString(); }### Answer:
@Test public void testEquals() { SimpleOomage ooA = new SimpleOomage(5, 10, 20); SimpleOomage ooA2 = new SimpleOomage(5, 10, 20); SimpleOomage ooB = new SimpleOomage(50, 50, 50); assertEquals(ooA, ooA2); assertNotEquals(ooA, ooB); assertNotEquals(ooA2, ooB); assertNotEquals(ooA, "ketchup"); } |
### Question:
SimpleOomage implements Oomage { public static SimpleOomage randomSimpleOomage() { int red = StdRandom.uniform(0, 51) * 5; int green = StdRandom.uniform(0, 51) * 5; int blue = StdRandom.uniform(0, 51) * 5; return new SimpleOomage(red, green, blue); } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); @Override void draw(double x, double y, double scalingFactor); static SimpleOomage randomSimpleOomage(); static void main(String[] args); String toString(); }### Answer:
@Test public void testRandomOomagesHashCodeSpread() { List<Oomage> oomages = new ArrayList<>(); int N = 10000; for (int i = 0; i < N; i += 1) { oomages.add(SimpleOomage.randomSimpleOomage()); } assertTrue(OomageTestUtility.haveNiceHashCodeSpread(oomages, 10)); } |
### Question:
Clorus extends Creature { @Override public Clorus replicate() { energy /= 2; return new Clorus(energy); } Clorus(double energy); @Override void move(); @Override void attack(Creature c); @Override Clorus replicate(); @Override void stay(); @Override Action chooseAction(Map<Direction, Occupant> neighbors); @Override Color color(); }### Answer:
@Test public void testReplicate() { Clorus c = new Clorus(2); Clorus offspring = c.replicate(); assertEquals(1, c.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(c, offspring); } |
### Question:
Plip extends Creature { public Plip replicate() { energy /= 2; return new Plip(energy); } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); }### Answer:
@Test public void testReplicate() { Plip p = new Plip(2); Plip offspring = p.replicate(); assertEquals(1, p.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(p, offspring); } |
### Question:
StringWritableCsv { public static StringBuffer writeTo(StringBuffer sb, StringWritable... values) throws IllegalArgumentException { checkNotNull(sb, "sb"); if(null == values || values.length == 0) { return sb; } writeStringWritableToStringBuffer(values[0], sb); int i = 1; while (i < values.length) { sb.append(','); writeStringWritableToStringBuffer(values[i], sb); i++; } return sb; } static StringBuffer writeTo(StringBuffer sb, StringWritable... values); static String[] parseFrom(String value, int n, int offset); static String[] parseFrom(String value, int n); static String[] parseFrom(String value); }### Answer:
@Test public void writeToNullOrEmpty() { assertTrue(StringWritableCsv.writeTo(new StringBuffer()).length() == 0); assertTrue(StringWritableCsv.writeTo(new StringBuffer(), new CharAttributeValue[]{}).length() == 0); }
@Test public void writeToOneArg() { CharAttributeValue[] pairs = new CharAttributeValue[] { new ScramAttributeValue(ScramAttributes.CHANNEL_BINDING, "channel"), new ScramAttributeValue(ScramAttributes.ITERATION, "" + 4096), new Gs2AttributeValue(Gs2Attributes.AUTHZID, "authzid"), new Gs2AttributeValue(Gs2Attributes.CLIENT_NOT, null) }; for(int i = 0; i < pairs.length; i++) { assertEquals(ONE_ARG_VALUES[i], StringWritableCsv.writeTo(new StringBuffer(), pairs[i]).toString()); } }
@Test public void writeToSeveralArgs() { assertEquals( SEVERAL_VALUES_STRING, StringWritableCsv.writeTo( new StringBuffer(), new Gs2AttributeValue(Gs2Attributes.CLIENT_NOT, null), null, new ScramAttributeValue(ScramAttributes.USERNAME, "user"), new ScramAttributeValue(ScramAttributes.NONCE, "fyko+d2lbbFgONRv9qkxdawL") ).toString() ); } |
### Question:
ServerFirstMessage implements StringWritable { @Override public String toString() { return writeTo(new StringBuffer()).toString(); } ServerFirstMessage(
String clientNonce, String serverNonce, String salt, int iteration
); String getClientNonce(); String getServerNonce(); String getNonce(); String getSalt(); int getIteration(); @Override StringBuffer writeTo(StringBuffer sb); static ServerFirstMessage parseFrom(String serverFirstMessage, String clientNonce); @Override String toString(); static final int ITERATION_MIN_VALUE; }### Answer:
@Test public void validConstructor() { ServerFirstMessage serverFirstMessage = new ServerFirstMessage( CLIENT_NONCE, "3rfcNHYJY1ZVvWVs7j", "QSXCR+Q6sek8bf92", 4096 ); assertEquals(SERVER_FIRST_MESSAGE, serverFirstMessage.toString()); } |
### Question:
ScramStringFormatting { public static String toSaslName(String value) { if(null == value || value.isEmpty()) { return value; } int nComma = 0, nEqual = 0; char[] originalChars = value.toCharArray(); for(char c : originalChars) { if(',' == c) { nComma++; } else if('=' == c) { nEqual++; } } if(nComma == 0 && nEqual == 0) { return value; } char[] saslChars = new char[originalChars.length + nComma * 2 + nEqual * 2]; int i = 0; for(char c : originalChars) { if(',' == c) { saslChars[i++] = '='; saslChars[i++] = '2'; saslChars[i++] = 'C'; } else if('=' == c) { saslChars[i++] = '='; saslChars[i++] = '3'; saslChars[i++] = 'D'; } else { saslChars[i++] = c; } } return new String(saslChars); } static String toSaslName(String value); static String fromSaslName(String value); static String base64Encode(byte[] value); static String base64Encode(String value); static byte[] base64Decode(String value); }### Answer:
@Test public void toSaslNameNoCharactersToBeEscaped() { for(String s : VALUES_NO_CHARS_TO_BE_ESCAPED) { assertEquals(s, ScramStringFormatting.toSaslName(s)); } }
@Test public void toSaslNameWithCharactersToBeEscaped() { for(int i = 0; i < VALUES_TO_BE_ESCAPED.length; i++) { assertEquals(ESCAPED_VALUES[i], ScramStringFormatting.toSaslName(VALUES_TO_BE_ESCAPED[i])); } } |
### Question:
ScramFunctions { public static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, CLIENT_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void clientKey() { assertBytesEqualsBase64("4jTEe/bDZpbdbYUrmaqiuiZVVyg=", generateClientKey()); } |
### Question:
ScramFunctions { public static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey) { return hash(scramMechanism, clientKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void storedKey() { assertBytesEqualsBase64("6dlGYMOdZcOPutkcNY8U2g7vK9Y=", generateStoredKey()); } |
### Question:
ScramFunctions { public static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, SERVER_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void serverKey() { assertBytesEqualsBase64("D+CSWLOshSulAsxiupA+qs2/fTE=", generateServerKey()); } |
### Question:
ScramFunctions { public static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage) { return hmac(scramMechanism, authMessage.getBytes(StandardCharsets.UTF_8), storedKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void clientSignature() { assertBytesEqualsBase64("XXE4xIawv6vfSePi2ovW5cedthM=", generateClientSignature()); } |
### Question:
ScramFunctions { public static byte[] clientProof(byte[] clientKey, byte[] clientSignature) { return CryptoUtil.xor(clientKey, clientSignature); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void clientProof() { assertBytesEqualsBase64("v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=", generateClientProof()); } |
### Question:
ScramFunctions { public static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage) { return clientSignature(scramMechanism, serverKey, authMessage); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void serverSignature() { assertBytesEqualsBase64("rmF9pqV8S7suAoZWja4dJRkFsKQ=", generateServerSignature()); } |
### Question:
ScramFunctions { public static boolean verifyServerSignature( ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature ) { return Arrays.equals(serverSignature(scramMechanism, serverKey, authMessage), serverSignature); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); }### Answer:
@Test public void verifyServerSignature() { assertTrue( ScramFunctions.verifyServerSignature( ScramMechanisms.SCRAM_SHA_1, generateServerKey(), AUTH_MESSAGE, generateServerSignature() ) ); } |
### Question:
Gs2AttributeValue extends AbstractCharAttributeValue { public static Gs2AttributeValue parse(String value) throws IllegalArgumentException { if(null == value) { return null; } if(value.length() < 1 || value.length() == 2 || (value.length() > 2 && value.charAt(1) != '=')) { throw new IllegalArgumentException("Invalid Gs2AttributeValue"); } return new Gs2AttributeValue( Gs2Attributes.byChar(value.charAt(0)), value.length() > 2 ? value.substring(2) : null ); } Gs2AttributeValue(Gs2Attributes attribute, String value); static StringBuffer writeTo(StringBuffer sb, Gs2Attributes attribute, String value); static Gs2AttributeValue parse(String value); }### Answer:
@Test public void parseNullValue() { assertNull(Gs2AttributeValue.parse(null)); }
@Test public void parseIllegalValuesStructure() { String[] values = new String[] { "", "as", "asdfjkl", Gs2Attributes.CHANNEL_BINDING_REQUIRED.getChar() + "=" }; int n = 0; for(String value : values) { try { assertNotNull(Gs2AttributeValue.parse(value)); } catch(IllegalArgumentException e) { n++; } } assertEquals("Not every illegal value thrown IllegalArgumentException", values.length, n); }
@Test public void parseIllegalValuesInvalidGS2Attibute() { String[] values = new String[] { "z=asdfasdf", "i=value" }; int n = 0; for(String value : values) { try { assertNotNull(Gs2AttributeValue.parse(value)); } catch(IllegalArgumentException e) { n++; } } assertEquals("Not every illegal value thrown IllegalArgumentException", values.length, n); }
@Test public void parseLegalValues() { String[] values = new String[] { "n", "y", "p=value", "a=authzid" }; for(String value : values) { assertNotNull(Gs2AttributeValue.parse(value)); } } |
### Question:
Gs2Header extends AbstractStringWritable { public static Gs2Header parseFrom(String message) throws IllegalArgumentException { checkNotNull(message, "Null message"); String[] gs2HeaderSplit = StringWritableCsv.parseFrom(message, 2); if(gs2HeaderSplit.length == 0) { throw new IllegalArgumentException("Invalid number of fields for the GS2 Header"); } Gs2AttributeValue gs2cbind = Gs2AttributeValue.parse(gs2HeaderSplit[0]); return new Gs2Header( Gs2CbindFlag.byChar(gs2cbind.getChar()), gs2cbind.getValue(), gs2HeaderSplit[1] == null || gs2HeaderSplit[1].isEmpty() ? null : Gs2AttributeValue.parse(gs2HeaderSplit[1]).getValue() ); } Gs2Header(Gs2CbindFlag cbindFlag, String cbName, String authzid); Gs2Header(Gs2CbindFlag cbindFlag, String cbName); Gs2Header(Gs2CbindFlag cbindFlag); Gs2CbindFlag getChannelBindingFlag(); Optional<String> getChannelBindingName(); Optional<String> getAuthzid(); @Override StringBuffer writeTo(StringBuffer sb); static Gs2Header parseFrom(String message); }### Answer:
@Test public void parseFromInvalid() { String[] invalids = new String[] { "Z,", "n,Z=blah", "p,", "n=a," }; int n = 0; for(String invalid : invalids) { try { Gs2Header.parseFrom(invalid); System.out.println(invalid); } catch (IllegalArgumentException e) { n++; } } assertEquals(invalids.length, n); } |
### Question:
ScramClient { public static List<String> supportedMechanisms() { return Arrays.stream(ScramMechanisms.values()).map(m -> m.getName()).collect(Collectors.toList()); } private ScramClient(
ChannelBinding channelBinding, StringPreparation stringPreparation,
Optional<ScramMechanism> nonChannelBindingMechanism, Optional<ScramMechanism> channelBindingMechanism,
SecureRandom secureRandom, Supplier<String> nonceSupplier
); static PreBuilder1 channelBinding(ChannelBinding channelBinding); StringPreparation getStringPreparation(); ScramMechanism getScramMechanism(); static List<String> supportedMechanisms(); ScramSession scramSession(String user); static final int DEFAULT_NONCE_LENGTH; }### Answer:
@Test public void supportedMechanismsTestAll() { assertArrayEquals( Arrays.stream( new String[] { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" } ).sorted().toArray(), ScramClient.supportedMechanisms().stream().sorted().toArray() ); } |
### Question:
CryptoUtil { public static String nonce(int size, SecureRandom random) { if(size <= 0) { throw new IllegalArgumentException("Size must be positive"); } char[] chars = new char[size]; int r; for(int i = 0; i < size;) { r = random.nextInt(MAX_ASCII_PRINTABLE_RANGE - MIN_ASCII_PRINTABLE_RANGE + 1) + MIN_ASCII_PRINTABLE_RANGE; if(r != EXCLUDED_CHAR) { chars[i++] = (char) r; } } return new String(chars); } static String nonce(int size, SecureRandom random); static String nonce(int size); static byte[] hi(
SecretKeyFactory secretKeyFactory, int keyLength, String value, byte[] salt, int iterations
); static byte[] hmac(SecretKeySpec secretKeySpec, Mac mac, byte[] message); static byte[] xor(byte[] value1, byte[] value2); }### Answer:
@Test(expected = IllegalArgumentException.class) public void nonceInvalidSize1() { CryptoUtil.nonce(0, SECURE_RANDOM); }
@Test(expected = IllegalArgumentException.class) public void nonceInvalidSize2() { CryptoUtil.nonce(-1, SECURE_RANDOM); }
@Test public void nonceValid() { int nNonces = 1000; int nonceMaxSize = 100; Random random = new Random(); for(int i = 0; i < nNonces; i++) { for(char c : CryptoUtil.nonce(random.nextInt(nonceMaxSize) + 1, SECURE_RANDOM).toCharArray()) { if(c == ',' || c < (char) 33 || c > (char) 126) { fail("Character c='" + c + "' is not allowed on a nonce"); } } } } |
### Question:
YAMLFileParameterizer { protected static String normalizeFilename(String filename) { return StringUtils.trimToEmpty(filename).replaceAll("\\\\|/", "\\"+File.separator); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; }### Answer:
@Test public void testNormalizeFilename() { String s1="/a/b/c\\d.txt"; String s2="\\a\\b\\c\\d.txt"; String expected = String.format("%sa%sb%sc%sd.txt", File.separator, File.separator, File.separator, File.separator); String ns1 = YAMLFileParameterizer.normalizeFilename(s1); String ns2 = YAMLFileParameterizer.normalizeFilename(s2); assertTrue(expected.equals(ns1)); assertTrue(expected.equals(ns2)); } |
### Question:
HybridServiceGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-service"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); }### Answer:
@Test public void testGetFramework() { HybridServiceGenerator generator = new HybridServiceGenerator(); Assert.assertEquals("light-hybrid-4j-service", generator.getFramework()); } |
### Question:
HybridServerGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-server"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); }### Answer:
@Test public void testGetFramework() { HybridServerGenerator generator = new HybridServerGenerator(); Assert.assertEquals("light-hybrid-4j-server", generator.getFramework()); } |
### Question:
GraphqlGenerator implements Generator { @Override public String getFramework() { return "light-graphql-4j"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); }### Answer:
@Test public void testGetFramework() { GraphqlGenerator generator = new GraphqlGenerator(); Assert.assertEquals("light-graphql-4j", generator.getFramework()); } |
### Question:
YAMLFileParameterizer { protected static Set<String> buildFileExcludeSet(String sourceDir, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildFileExcludeSet(sourceDir, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; }### Answer:
@Test public void testFileExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("/a/b/c\\d.txt"), Any.wrap("2.yml"), Any.wrap("\\a\\b\\c\\d.txt"), Any.wrap("")); Set<String> excludeSet = YAMLFileParameterizer.buildFileExcludeSet(".",excludes); assertTrue(2==excludeSet.size()); } |
### Question:
YAMLFileParameterizer { protected static Set<String> buildResourceExcludeSet(String resourceLocation, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildResourceExcludeSet(resourceLocation, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; }### Answer:
@Test public void testResourceExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("audit.yml"), Any.wrap("body.yml")); Set<String> excludeSet = YAMLFileParameterizer.buildResourceExcludeSet("handlerconfig/", excludes); assertTrue(2==excludeSet.size()); } |
### Question:
Utils { public static String camelize(String word) { return camelize(word, false); } static String camelize(String word); static String camelize(String word, boolean lowercaseFirstLetter); static boolean isUrl(String location); static byte[] urlToByteArray(URL url); }### Answer:
@Test public void testUnderscoreToLowerCamel() { for (Map.Entry<String, String> entry : underscoreToLowerCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey(), true)); } }
@Test public void testUnderscoreToCamel() { for (Map.Entry<String, String> entry : underscoreToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } }
@Test public void testSlashToCamel() { for (Map.Entry<String, String> entry : slashToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } }
@Test public void testCamelToUnderscore() { for (Map.Entry<String, String> entry : camelToUnderscore_.entrySet()) { Assert.assertEquals(entry.getKey(), Utils.camelize(entry.getValue())); } }
@Test public void testDashToCamel() { for (Map.Entry<String, String> entry : dashToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } } |
### Question:
Token { public static boolean isValid(final String token) { if (token == null || token.length() == 0) { return false; } final int len = token.length(); for (int i = 0; i < len; ++i) { if (isSeparator(token.charAt(i))) { return false; } } return true; } static boolean isSeparator(final char ch); static boolean isValid(final String token); static String unescape(final String text); static String unquote(String text); }### Answer:
@Test public void test004() { isValid("abc"); } |
### Question:
Accept extends AbstractFrameFilter implements FrameFilter { @Override public boolean process(TransactionContext context) { if (expression != null) { String resolvedExpression = Template.preProcess(expression, getContext().getSymbols()); try { if (evaluator.evaluateBoolean(resolvedExpression)) { if (Log.isLogging(Log.DEBUG_EVENTS)) { Log.debug("Accepted frame " + context.getRow()); } return false; } else { if (Log.isLogging(Log.DEBUG_EVENTS)) { Log.debug("Did not pass accept expression of '" + resolvedExpression + "'"); } } } catch (IllegalArgumentException e) { Log.warn(LogMsg.createMsg(CDX.MSG, "Filter.accept_boolean_evaluation_error", e.getMessage())); } } return true; } Accept(); Accept(String condition); @Override boolean process(TransactionContext context); }### Answer:
@Test public void testAcceptContext() { Accept filter = new Accept(); String expression = "match( Working.Record Type , PO )"; filter.setCondition(expression); filter.open(transformContext); assertFalse(filter.process(context)); assertNotNull(context.getWorkingFrame()); } |
### Question:
TransformContext extends OperationalContext { public Object resolveToValue(final String token) { Object retval = null; if (StringUtil.isNotEmpty(token)) { final Object value = resolveFieldValue(token); if (value != null) { retval = value; } else { final Object obj = searchForValue(token); if (obj != null) { retval = obj; } else { if (symbols != null && symbols.containsKey(token)) { retval = symbols.get(token); } } } } return retval; } TransformContext(); TransformContext(final List<ContextListener> listeners); void close(); boolean containsField(final String token); Config getConfiguration(); TransactionContext getTransaction(); @SuppressWarnings("unchecked") void open(); void reset(); String resolveArgument(final String value); String resolveField(final String token); Object resolveFieldValue(final String token); String resolveToString(final String token); Object resolveToValue(final String token); void setConfiguration(final Config config); void setEngine(final TransformEngine engine); void setTransaction(final TransactionContext context); TransformEngine getEngine(); static final String DISPOSITION; static final String ENDTIME; static final String ERROR_MSG; static final String ERROR_STATE; static final String FRAME_COUNT; static final String STARTTIME; }### Answer:
@Test public void resolveToValue() { assertNull(transformContext.resolveFieldValue("one")); assertNotNull(transformContext.resolveFieldValue("Source.Field2")); assertNotNull(transformContext.resolveFieldValue("Working.Field4")); assertNotNull(transformContext.resolveFieldValue("Target.Field6")); assertNull(transformContext.resolveToValue("nested")); assertNotNull(transformContext.resolveToValue("Nested")); assertNotNull(transformContext.resolveToValue("Nested.bird")); assertNotNull(transformContext.resolveToValue("Map.legend")); assertNotNull(transformContext.resolveToValue("Map.path.secret")); } |
### Question:
FileContext extends PersistentContext { public FileContext() { } FileContext(); @Override void open(); @Override void close(); }### Answer:
@Test public void fileContext() { String jobName = "ContextTest"; DataFrame config = new DataFrame().set("fields", new DataFrame().set("SomeKey", "SomeValue").set("AnotherKey", "AnotherValue")); TransformEngine engine = new DefaultTransformEngine(); engine.setName(jobName); TransformContext context = new FileContext(); 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); SymbolTable symbols = engine.getSymbolTable(); obj = symbols.get(Symbols.CURRENT_RUN_MILLIS); assertTrue(obj instanceof Long); long millis = (Long)obj; obj = symbols.get(Symbols.CURRENT_RUN_SECONDS); assertTrue(obj instanceof Long); long seconds = (Long)obj; assertTrue(seconds == (millis / 1000)); turnOver(engine); obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long nextRunCount = (Long)obj; assertEquals(runcount + 1, nextRunCount); context = new FileContext(); 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); } |
### Question:
NotEmpty extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { String value = field.getStringValue(); if (StringUtil.isBlank(value)) { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName, "There is no working frame"); } return retval; } NotEmpty(); @Override boolean process(TransactionContext context); }### Answer:
@Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("model", "PT4500"); context.setSourceFrame(sourceFrame); try (FrameValidator validator = new NotEmpty()) { validator.setConfiguration(configuration); validator.open(getTransformContext()); boolean result = validator.process(context); assertTrue(result); sourceFrame = new DataFrame(); sourceFrame.put("model", " "); context.setSourceFrame(sourceFrame); result = validator.process(context); assertFalse(result); } catch (ConfigurationException | ValidationException | IOException e) { e.printStackTrace(); fail(e.getMessage()); } } |
### Question:
NotNull extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { if (field.isNull()) { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName, "There is no working frame"); } return retval; } NotNull(); @Override boolean process(TransactionContext context); }### Answer:
@Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); FrameValidator validator = new NotNull(); try { validator.setConfiguration(configuration); } catch (ConfigurationException e) { e.printStackTrace(); fail(e.getMessage()); } validator.open(getTransformContext()); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("model", "PT4500"); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertTrue(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } context = createTransactionContext(); sourceFrame = new DataFrame(); sourceFrame.put("model", " "); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertTrue(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } context = createTransactionContext(); sourceFrame = new DataFrame(); sourceFrame.put("model", null); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertFalse(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } } |
### Question:
Pagination { public synchronized void step() { offset += step; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); }### Answer:
@Test public void testStep() { Pagination page = new Pagination(5); assertEquals("page", page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); } |
### Question:
Pagination { public synchronized void reset() { this.offset = start; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); }### Answer:
@Test public void testReset() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); page.step(); page.step(); page.step(); page.step(); page.step(); assertTrue(page.getOffset() == 30); assertTrue(page.getEnd() == 35); page.reset(); assertTrue(page.getOffset() == 0); assertTrue(page.getEnd() == 5); } |
### Question:
Pagination { @SuppressWarnings("unchecked") public synchronized SymbolTable toSymbolTable() { SymbolTable retval = new SymbolTable(); retval.put(name + ".start", getOffset()); retval.put(name + ".size", getStep()); retval.put(name + ".end", getEnd()); return retval; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); }### Answer:
@Test public void testToSymbolTable() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); SymbolTable symbols = page.toSymbolTable(); assertNotNull(symbols); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".start"))); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".size"))); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".end"))); assertTrue(StringUtil.isBlank(symbols.getString(NAME + ".pickle"))); } |
### Question:
Pagination { public String getName() { return name; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); }### Answer:
@Test public void blankName() { Pagination page = new Pagination("", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(" ", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(null, 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); } |
### Question:
Token { public static String unquote(String text) { if (text == null) { return null; } final int len = text.length(); if (len < 2 || text.charAt(0) != '"' || text.charAt(len - 1) != '"') { return text; } text = text.substring(1, len - 1); return unescape(text); } static boolean isSeparator(final char ch); static boolean isValid(final String token); static String unescape(final String text); static String unquote(String text); }### Answer:
@Test public void test014() { unquote("abc", "\"abc\""); }
@Test public void test015() { unquote("\"abc", "\"abc"); }
@Test public void test016() { unquote("abc\"", "abc\""); }
@Test public void test017() { unquote("abc", "\"ab\\c\""); }
@Test public void test018() { unquote("ab\\c", "\"ab\\\\c\""); }
@Test public void test011() { unquote(null, null); }
@Test public void test012() { unquote("", ""); }
@Test public void test013() { unquote("abc", "abc"); } |
### Question:
Pagination { @Override public String toString() { StringBuilder b = new StringBuilder("Pagination: '"); b.append(getName()); b.append("' start:").append(getStart()); b.append(" step:").append(getStep()); return b.toString(); } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); }### Answer:
@Test public void toStringTest() { final String expected = "Pagination: 'offset' start:0 step:5"; final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(expected, page.toString()); } |
### Question:
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(); }### Answer:
@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("-")); } |
### Question:
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(); }### Answer:
@Test public void toTimeFormat() { String queryFormat = new SnowDateTime(new Date()).toTimeFormat(); assertNotNull(queryFormat); assertTrue(queryFormat.contains(":")); } |
### Question:
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; }### Answer:
@Test public void snowFilter() { SnowFilter filter = new SnowFilter(); assertNotNull(filter); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@Test public void testAccept() {} |
### Question:
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); }### Answer:
@Test public void testWildcardMatch() {} |
### Question:
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); }### Answer:
@Test public void testSplitOnTokens() {} |
### Question:
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); }### Answer:
@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 ); } |
### Question:
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); }### Answer:
@Test public void testFunctionArgumentSeparators() { Parameters params = DoubleEvaluator.getDefaultParameters(); params.setFunctionArgumentSeparator( ';' ); DoubleEvaluator evaluator = new DoubleEvaluator( params ); assertEquals( 2, evaluator.evaluate( "avg(3;1)" ), 0.001 ); } |
### Question:
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); }### Answer:
@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 ); } |
### Question:
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); }### Answer:
@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)); } } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
Evaluator { public Evaluator() { } Evaluator(); Evaluator( final TransformContext context ); boolean evaluateBoolean( final String expression ); double evaluateNumeric( final String expression ); void setContext( final TransformContext context ); }### Answer:
@Test public void testEvaluator() { final Evaluator subject = new Evaluator(); assertNotNull(subject); } |
### Question:
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 ); }### Answer:
@Test public void testSetContext() { evaluator.setContext(transformContext); } |
### Question:
OriginUri { URI uri() { return uri; } OriginUri(HttpCookie cookie, URI associated); }### Answer:
@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: } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void shouldBeAbleToRemoveCookie() { addCookies(1, false); CookieStore store = new CookieTray(preferences); store.remove(URI.create("http: verify(editor).remove("http: } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void shouldFilterCookiesOutByUri() { addCookies(10, false); CookieStore store = new CookieTray(preferences); assertEquals(1, store.get(URI.create("http: } |
### Question:
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(); }### Answer:
@Test public void _2_connectionFailureShouldBeDetected() throws Exception { suroServer.getInjector().getInstance(InputManager.class).getInput("thrift").shutdown(); HttpResponse response = runQuery("surohealthcheck"); assertEquals(500, response.getStatusLine().getStatusCode()); } |
### Question:
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; }### Answer:
@Test public void testAlwaysFalse() { assertFalse(AlwaysFalseMessageFilter.INSTANCE.apply(DUMMY_INPUT)); } |
### Question:
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(); }### Answer:
@Test public void testNotTrueIsFalse() { assertFalse(new NotMessageFilter(getTrueFilter()).apply(DUMMY_INPUT)); }
@Test public void testNotFalseIsTrue() { assertTrue(new NotMessageFilter(getFalseFilter()).apply(DUMMY_INPUT)); } |
### Question:
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); }### Answer:
@Test public void testAlwaysFalseReturnsFalse() { assertFalse(alwaysFalse().apply(DUMMY_INPUT)); } |
### Question:
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); }### Answer:
@Test public void testAlwaysTrueReturnsTrue() { assertTrue(alwaysTrue().apply(DUMMY_INPUT)); } |
### Question:
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); }### Answer:
@Test public void testNotAlwaysNegates(){ assertTrue(not(getFalseFilter()).apply(DUMMY_INPUT)); assertFalse(not(getTrueFilter()).apply(DUMMY_INPUT)); } |
### Question:
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); }### Answer:
@Test public void testOr() { assertTrue(or(getFalseFilter(), getFalseFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(or(getFalseFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } |
### Question:
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); }### Answer:
@Test public void testAnd(){ assertTrue(and(getTrueFilter(), getTrueFilter()).apply(DUMMY_INPUT)); assertFalse(and(getTrueFilter(), getFalseFilter()).apply(DUMMY_INPUT)); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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!!!"); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.