method2testcases
stringlengths 118
6.63k
|
---|
### Question:
DoubleRangeValidator extends CustomValidator<Double> { public static DoubleRangeValidator exactly(double value, String errorMessage) { return new DoubleRangeValidator(value, value, errorMessage); } private DoubleRangeValidator(double min, double max, String errorMessage); static DoubleRangeValidator between(double min, double max, String errorMessage); static DoubleRangeValidator atLeast(double min, String errorMessage); static DoubleRangeValidator upTo(double max, String errorMessage); static DoubleRangeValidator exactly(double value, String errorMessage); }### Answer:
@Test public void exactlyTest() { DoubleRangeValidator i = DoubleRangeValidator.exactly(3.14, "test"); Assert.assertFalse(i.validate(-3.4).getResult()); Assert.assertFalse(i.validate(3.145).getResult()); Assert.assertTrue(i.validate(3.14).getResult()); Assert.assertFalse(i.validate(3.0).getResult()); Assert.assertFalse(i.validate(Double.MIN_VALUE).getResult()); } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> between(int min, int max, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } else if (min > max) { throw new IllegalArgumentException("Minimum must not be larger than maximum."); } return new SelectionLengthValidator<>(min, max, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void betweenTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.between(1, 3, "test"); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3, 4, 5)).getResult()); try { SelectionLengthValidator s2 = SelectionLengthValidator.between(-10, 2, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { SelectionLengthValidator s3 = SelectionLengthValidator.between(0, 0, "test"); } catch (IllegalArgumentException e) { fail(); } try { SelectionLengthValidator s4 = SelectionLengthValidator.between(10, 1, "test"); fail(); } catch (IllegalArgumentException ignored) {} } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> atLeast(int min, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } return new SelectionLengthValidator<>(min, Integer.MAX_VALUE, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void atLeastTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.atLeast(2, "test"); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 4)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); try { SelectionLengthValidator s2 = SelectionLengthValidator.atLeast(-10, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { SelectionLengthValidator s3 = SelectionLengthValidator.atLeast(0, "test"); } catch (IllegalArgumentException e) { fail(); } } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> upTo(int max, String errorMessage) { return new SelectionLengthValidator<>(0, max, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void upToTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.upTo(2, "test"); Assert.assertFalse(s.validate(FXCollections.observableArrayList(3, 5, 1)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3, 5, 14)).getResult()); } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> exactly(int value, String errorMessage) { return new SelectionLengthValidator<>(value, value, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void exactlyTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.exactly(2, "test"); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1)).getResult()); } |
### Question:
Octagons extends StructuredArray<Octagon> { public static Octagons newInstance(final long length) { return StructuredArray.newInstance(Octagons.class, Octagon.class, length); } Octagons(); Octagons(Octagons source); static Octagons newInstance(final long length); static Octagons newInstance(
final long length,
final CtorAndArgsProvider<Octagon> ctorAndArgsProvider); static Octagons newInstance(
final long length,
final String color,
final long initialCenterX,
final long initialCenterY,
final long radius,
final long deltaX,
final long deltaY); public Date creationDate; }### Answer:
@Test public void shouldConstructOctagon() throws NoSuchMethodException { Octagons octagons = Octagons.newInstance( 100, "Orange", 0, 0 , 20 , 100, 100 ); PointArray points = octagons.get(0).getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(20L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(0L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(14L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(-14L)); points = octagons.get(10).getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(1000 + 20L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(1000 + 0L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(1000 + 14L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(1000 + -14L)); Octagons octagons2 = Octagons.copyInstance(octagons); points = octagons2.get(0).getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(20L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(0L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(14L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(-14L)); points = octagons.get(10).getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(1000 + 20L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(1000 + 0L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(1000 + 14L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(1000 + -14L)); } |
### Question:
Octagon { public PointArray getPoints() { return points; } Octagon(); Octagon(final String color); Octagon(final Octagon source); Octagon(final String color, final long centerX, final long centerY, final long radius); PointArray getPoints(); String getColor(); }### Answer:
@Test public void shouldConstructOctagon() throws NoSuchMethodException { Octagon octagon = new Octagon(); PointArray points = octagon.getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(0L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(0L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(0L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(0L)); int i = 0; for (Point p : points) { p.setX(++i); p.setY(++i); } Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(1L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(2L)); Assert.assertThat(valueOf(points.get(1).getX()), CoreMatchers.is(3L)); Assert.assertThat(valueOf(points.get(1).getY()), CoreMatchers.is(4L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(15L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(16L)); Octagon octagon2 = new Octagon(octagon); points = octagon2.getPoints(); Assert.assertThat(valueOf(points.get(0).getX()), CoreMatchers.is(1L)); Assert.assertThat(valueOf(points.get(0).getY()), CoreMatchers.is(2L)); Assert.assertThat(valueOf(points.get(1).getX()), CoreMatchers.is(3L)); Assert.assertThat(valueOf(points.get(1).getY()), CoreMatchers.is(4L)); Assert.assertThat(valueOf(points.get(7).getX()), CoreMatchers.is(15L)); Assert.assertThat(valueOf(points.get(7).getY()), CoreMatchers.is(16L)); } |
### Question:
StructuredArrayOfAtomicLong extends StructuredArray<AtomicLong> { public static StructuredArrayOfAtomicLong newInstance(final long length) { return StructuredArray.newInstance(StructuredArrayOfAtomicLong.class, AtomicLong.class, length); } static StructuredArrayOfAtomicLong newInstance(final long length); AtomicLong get(long index); }### Answer:
@Test public void shouldInitializeToCorrectValues() { final long length = 1444; final StructuredArrayOfAtomicLong array = StructuredArrayOfAtomicLong.newInstance(length); initSumValues(array); assertCorrectVariableInitialisation(length, array); } |
### Question:
SignatureMethodsHMAC256Impl implements SignatureMethod<SymmetricKeyImpl, SymmetricKeyImpl> { @Override public String calculate(String header, String payload, SymmetricKeyImpl signingKey) { StringBuilder sb = new StringBuilder(); sb.append(header).append(".").append(payload); String stringToSign = sb.toString(); byte[] bytes = stringToSign.getBytes(); try { Mac mac = Mac.getInstance("HMACSHA256"); mac.init(new SecretKeySpec(signingKey.getKey(), mac.getAlgorithm())); mac.update(bytes); bytes = mac.doFinal(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } return TokenDecoder.base64Encode(bytes); } @Override String calculate(String header, String payload, SymmetricKeyImpl signingKey); @Override boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey); @Override String getAlgorithm(); }### Answer:
@Test public void testCalculate() { assertEquals("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", sHmacImpl.calculate(TokenDecoder.base64Encode(hs256), TokenDecoder.base64Encode(payload), key)); } |
### Question:
TokenReader extends TokenDecoder { public T read(String base64String) { if (base64String == null || base64String.isEmpty()) { throw new IllegalArgumentException("Impossible to obtain a Token from a null or empty string"); } StringBuilder buffer = new StringBuilder(); BufferedReader reader = new BufferedReader(new StringReader(base64String)); String line = null; try { while ((line = reader.readLine()) != null) { buffer.append(line.trim()); } } catch (IOException e) { } finally { try { reader.close(); } catch (IOException e) { } } Matcher matcher = base64urlTokenPattern.matcher(buffer.toString()); if (!matcher.matches()) { throw new IllegalArgumentException(base64String + "is not a valid Token, it does not match with the pattern: " + base64urlTokenPattern.pattern()); } String header = matcher.group(1); String decodedHeader = base64Decode(header); String body = matcher.group(2); String decodedBody = base64Decode(body); String signature = matcher.group(3); return build(base64String, decodedHeader, decodedBody, signature); } T read(String base64String); }### Answer:
@Test public void test_read2() { tokenReader = new TokenReader<String>() { protected String build(String rawString, String decodedHeader, String decodedBody, String encodedSignature) { return null; } }; String accessToken = "BadToken"; try { tokenReader.read(accessToken); Assert.fail("failed test"); }catch (IllegalArgumentException e) { } }
@Test public void test_read() { tokenReader = new TokenReader<String>() { protected String build(String rawString, String decodedHeader, String decodedBody, String encodedSignature) { return ""; } }; String accessToken = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"; Assert.assertNotNull(tokenReader.read(accessToken)); } |
### Question:
OAuthASResponse extends OAuthResponse { public static OAuthAuthorizationResponseBuilder authorizationResponse(HttpServletRequest request,int code) { return new OAuthAuthorizationResponseBuilder(request,code); } protected OAuthASResponse(String uri, int responseStatus); static OAuthAuthorizationResponseBuilder authorizationResponse(HttpServletRequest request,int code); static OAuthTokenResponseBuilder tokenResponse(int code); }### Answer:
@Test public void testAuthzResponse() throws Exception { HttpServletRequest request = createMock(HttpServletRequest.class); OAuthResponse oAuthResponse = OAuthASResponse.authorizationResponse(request,200) .location("http: .setCode("code") .setState("ok") .setParam("testValue", "value2") .buildQueryMessage(); String url = oAuthResponse.getLocationUri(); assertEquals("http: assertEquals(200, oAuthResponse.getResponseStatus()); }
@Test public void testAuthzResponseWithState() throws Exception { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getParameter(OAuth.OAUTH_STATE)).andStubReturn("ok"); replay(request); OAuthResponse oAuthResponse = OAuthASResponse.authorizationResponse(request,200) .location("http: .setCode("code") .setParam("testValue", "value2") .buildQueryMessage(); String url = oAuthResponse.getLocationUri(); assertEquals("http: assertEquals(200, oAuthResponse.getResponseStatus()); }
@Test public void testAuthzImplicitResponseWithState() throws Exception { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getParameter(OAuth.OAUTH_STATE)).andStubReturn("ok"); replay(request); OAuthResponse oAuthResponse = OAuthASResponse.authorizationResponse(request, 200) .location("http: .setAccessToken("access_111") .setTokenType("bearer") .setExpiresIn("400") .setParam("testValue", "value2") .buildQueryMessage(); String url = oAuthResponse.getLocationUri(); assertEquals("http: assertEquals(200, oAuthResponse.getResponseStatus()); }
@Test public void testHeaderResponse() throws Exception { HttpServletRequest request = createMock(HttpServletRequest.class); OAuthResponse oAuthResponse = OAuthASResponse.authorizationResponse(request,400).setCode("oauth_code") .setState("state_ok") .buildHeaderMessage(); String header = oAuthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE); assertEquals("Bearer code=\"oauth_code\",state=\"state_ok\"", header); header = oAuthResponse.getHeaders().get(OAuth.HeaderType.WWW_AUTHENTICATE); assertEquals("Bearer code=\"oauth_code\",state=\"state_ok\"", header); } |
### Question:
OAuthASResponse extends OAuthResponse { public static OAuthTokenResponseBuilder tokenResponse(int code) { return new OAuthTokenResponseBuilder(code); } protected OAuthASResponse(String uri, int responseStatus); static OAuthAuthorizationResponseBuilder authorizationResponse(HttpServletRequest request,int code); static OAuthTokenResponseBuilder tokenResponse(int code); }### Answer:
@Test public void testTokenResponse() throws Exception { OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token") .setTokenType("bearer").setExpiresIn("200").setRefreshToken("refresh_token2") .buildBodyMessage(); String body = oAuthResponse.getBody(); assertEquals( "access_token=access_token&refresh_token=refresh_token2&token_type=bearer&expires_in=200", body); }
@Test public void testTokenResponseAdditionalParam() throws Exception { OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token") .setTokenType("bearer").setExpiresIn("200").setRefreshToken("refresh_token2").setParam("some_param", "new_param") .buildBodyMessage(); String body = oAuthResponse.getBody(); assertEquals( "access_token=access_token&refresh_token=refresh_token2&some_param=new_param&token_type=bearer&expires_in=200", body); } |
### Question:
TokenValidator extends AbstractValidator<HttpServletRequest> { @Override public void validateMethod(HttpServletRequest request) throws OAuthProblemException { String method = request.getMethod(); if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) { throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) .description("Method not correct."); } } TokenValidator(); @Override void validateMethod(HttpServletRequest request); @Override void validateContentType(HttpServletRequest request); }### Answer:
@Test public void testValidateMethod() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.GET); replay(request); TokenValidator validator = new TokenValidator(); validator.validateMethod(request); verify(request); reset(request); request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.POST); replay(request); validator = new TokenValidator(); validator.validateMethod(request); verify(request); reset(request); request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.DELETE); replay(request); validator = new TokenValidator(); try { validator.validateMethod(request); Assert.fail("Expected validation exception"); } catch (OAuthProblemException e) { } verify(request); } |
### Question:
OAuthResponse implements OAuthMessage { public static OAuthErrorResponseBuilder errorResponse(int code) { return new OAuthErrorResponseBuilder(code); } protected OAuthResponse(String uri, int responseStatus); static OAuthResponseBuilder status(int code); static OAuthErrorResponseBuilder errorResponse(int code); @Override String getLocationUri(); @Override void setLocationUri(String uri); @Override String getBody(); @Override void setBody(String body); @Override String getHeader(String name); @Override Map<String, String> getHeaders(); @Override void setHeaders(Map<String, String> headers); int getResponseStatus(); @Override void addHeader(String name, String header); }### Answer:
@Test public void testErrorResponse() throws Exception { OAuthResponse oAuthResponse = OAuthResponse.errorResponse(400) .setError("error") .setRealm("album") .setState("ok") .setErrorDescription("error_description") .setErrorUri("http: .setParam("param", "value") .buildJSONMessage(); String body = oAuthResponse.getBody(); assertEquals( "{\"param\":\"value\",\"error_description\":\"error_description\",\"realm\":\"album\",\"state\":\"ok\",\"error\":\"error\",\"error_uri\":\"http: body); } |
### Question:
AbstractValidator implements OAuthValidator<T> { @Override public void validateContentType(T request) throws OAuthProblemException { String contentType = request.getContentType(); final String expectedContentType = OAuth.ContentType.URL_ENCODED; if (!OAuthUtils.hasContentType(contentType, expectedContentType)) { throw OAuthUtils.handleBadContentTypeException(expectedContentType); } } @Override void validateMethod(T request); @Override void validateContentType(T request); @Override void validateRequiredParameters(T request); @Override void validateOptionalParameters(T request); @Override void validateNotAllowedParameters(T request); @Override void validateClientAuthenticationCredentials(T request); @Override void performAllValidations(T request); }### Answer:
@Test public void testValidateContentType() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn(OAuth.ContentType.URL_ENCODED); replay(request); AbstractValidator validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); reset(request); expect(request.getContentType()).andStubReturn(OAuth.ContentType.URL_ENCODED + ";utf-8"); replay(request); validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); }
@Test(expected = OAuthProblemException.class) public void testInvalidContentType() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn(OAuth.ContentType.JSON); replay(request); AbstractValidator validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); } |
### Question:
SignatureMethodsHMAC256Impl implements SignatureMethod<SymmetricKeyImpl, SymmetricKeyImpl> { @Override public boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey) { String signed = calculate(header, payload, verifyingKey); return signed.equals(signature); } @Override String calculate(String header, String payload, SymmetricKeyImpl signingKey); @Override boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey); @Override String getAlgorithm(); }### Answer:
@Test public void testVerify() { String accessToken = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; String jwt[] = accessToken.split("\\."); assertTrue(sHmacImpl.verify(jwt[2], jwt[0], jwt[1], key)); } |
### Question:
JSONUtils { public static String buildJSON(Map<String, Object> params) { final StringWriter stringWriter = new StringWriter(); final JsonGenerator generator = GENERATOR_FACTORY.createGenerator(stringWriter); generator.writeStartObject(); for (Map.Entry<String, Object> param : params.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (key != null && value != null) { if (value instanceof Boolean) { generator.write(key, (Boolean) value); } else if (value instanceof Double) { generator.write(key, (Double) value); } else if (value instanceof Integer) { generator.write(key, (Integer) value); } else if (value instanceof BigDecimal) { generator.write(key, (BigDecimal) value); } else if (value instanceof BigInteger) { generator.write(key, (BigInteger) value); } else if (value instanceof Long) { generator.write(key, (Long) value); } else if (value instanceof String) { String string = (String) value; if (!string.isEmpty()) { generator.write(key, string); } } else if (value.getClass().isArray()) { generator.writeStartArray(key); for (int i = 0; i < Array.getLength(value); i++) { witeItem(generator, Array.get(value, i)); } generator.writeEnd(); } else if (value instanceof Collection) { generator.writeStartArray(key); Collection<?> collection = (Collection<?>) value; for (Object item : collection) { witeItem(generator, item); } generator.writeEnd(); } } } generator.writeEnd().close(); return stringWriter.toString(); } static String buildJSON(Map<String, Object> params); static Map<String, Object> parseJSON(String jsonBody); }### Answer:
@Test public void testBuildJSON() throws Exception { Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuthError.OAUTH_ERROR, OAuthError.TokenResponse.INVALID_REQUEST); String json = JSONUtils.buildJSON(params); assertEquals("{\"error\":\"invalid_request\"}", json); } |
### Question:
JSONUtils { public static Map<String, Object> parseJSON(String jsonBody) { final Map<String, Object> params = new HashMap<String, Object>(); StringReader reader = new StringReader(jsonBody); JsonReader jsonReader = Json.createReader(reader); JsonStructure structure = jsonReader.read(); if (structure == null || structure instanceof JsonArray) { throw new IllegalArgumentException(format("String '%s' is not a valid JSON object representation", jsonBody)); } JsonObject object = (JsonObject) structure; for (Entry<String, JsonValue> entry : object.entrySet()) { String key = entry.getKey(); if (key != null && !key.isEmpty()) { JsonValue jsonValue = entry.getValue(); if (jsonValue != null) { Object value = toJavaObject(jsonValue); params.put(key, value); } } } jsonReader.close(); return params; } static String buildJSON(Map<String, Object> params); static Map<String, Object> parseJSON(String jsonBody); }### Answer:
@Test public void testParseJson() throws Exception { Map<String, Object> jsonParams = new HashMap<String, Object>(); jsonParams.put("author", "John B. Smith"); jsonParams.put("year", "2000"); String s = JSONUtils.buildJSON(jsonParams); Map<String, Object> map = JSONUtils.parseJSON(s); assertEquals("John B. Smith", map.get("author")); assertEquals("2000", map.get("year")); } |
### Question:
OAuthUtils { public static String format( final Collection<? extends Map.Entry<String, Object>> parameters, final String encoding) { final StringBuilder result = new StringBuilder(); for (final Map.Entry<String, Object> parameter : parameters) { String value = parameter.getValue() == null? null : String.valueOf(parameter.getValue()); if (!OAuthUtils.isEmpty(parameter.getKey()) && !OAuthUtils.isEmpty(value)) { final String encodedName = encode(parameter.getKey(), encoding); final String encodedValue = value != null ? encode(value, encoding) : ""; if (result.length() > 0) { result.append(PARAMETER_SEPARATOR); } result.append(encodedName); result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } } return result.toString(); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testFormat() throws Exception { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("movie", "Kiler"); parameters.put("director", "Machulski"); String format = OAuthUtils.format(parameters.entrySet(), "UTF-8"); assertEquals("movie=Kiler&director=Machulski", format); } |
### Question:
OAuthUtils { public static String saveStreamAsString(InputStream is) throws IOException { return toString(is, ENCODING); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testSaveStreamAsString() throws Exception { String sampleTest = "It is raining again today"; InputStream is = new ByteArrayInputStream(sampleTest.getBytes("UTF-8")); assertEquals(sampleTest, OAuthUtils.saveStreamAsString(is)); } |
### Question:
OAuthUtils { public static OAuthProblemException handleOAuthProblemException(String message) { return OAuthProblemException.error(OAuthError.TokenResponse.INVALID_REQUEST) .description(message); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHandleOAuthProblemException() throws Exception { OAuthProblemException exception = OAuthUtils.handleOAuthProblemException("missing parameter"); assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, exception.getError()); assertEquals("missing parameter", exception.getDescription()); } |
### Question:
OAuthUtils { public static OAuthProblemException handleMissingParameters(Set<String> missingParams) { StringBuffer sb = new StringBuffer("Missing parameters: "); if (!OAuthUtils.isEmpty(missingParams)) { for (String missingParam : missingParams) { sb.append(missingParam).append(" "); } } return handleOAuthProblemException(sb.toString().trim()); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHandleMissingParameters() throws Exception { Set<String> missingParameters = new HashSet<String>(); missingParameters.add(OAuth.OAUTH_CLIENT_ID); missingParameters.add(OAuth.OAUTH_CLIENT_SECRET); OAuthUtils.handleMissingParameters(missingParameters); } |
### Question:
OAuthUtils { public static OAuthProblemException handleNotAllowedParametersOAuthException( List<String> notAllowedParams) { StringBuffer sb = new StringBuffer("Not allowed parameters: "); if (notAllowedParams != null) { for (String notAllowed : notAllowedParams) { sb.append(notAllowed).append(" "); } } return handleOAuthProblemException(sb.toString().trim()); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHandleNotAllowedParametersOAuthException() throws Exception { List<String> notAllowedParametersList = new LinkedList<String>(); notAllowedParametersList.add("Parameter1"); notAllowedParametersList.add("Parameter2"); OAuthProblemException exception = OAuthUtils.handleNotAllowedParametersOAuthException(notAllowedParametersList); assertEquals("Not allowed parameters: Parameter1 Parameter2", exception.getDescription()); } |
### Question:
OAuthUtils { public static Map<String, Object> decodeForm(String form) { Map<String, Object> params = new HashMap<String, Object>(); if (!OAuthUtils.isEmpty(form)) { for (String nvp : form.split("\\&")) { int equals = nvp.indexOf('='); String name; String value; if (equals < 0) { name = decodePercent(nvp); value = null; } else { name = decodePercent(nvp.substring(0, equals)); value = decodePercent(nvp.substring(equals + 1)); } params.put(name, value); } } return params; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testDecodeForm() throws Exception { String formUrlEncoded = "MyVariableOne=ValueOne&MyVariableTwo=ValueTwo"; Map<String, Object> formDecoded = OAuthUtils.decodeForm(formUrlEncoded); assertEquals(2, formDecoded.size()); assertEquals("ValueOne", formDecoded.get("MyVariableOne")); assertEquals("ValueTwo", formDecoded.get("MyVariableTwo")); } |
### Question:
OAuthUtils { public static boolean isFormEncoded(String contentType) { if (contentType == null) { return false; } int semi = contentType.indexOf(";"); if (semi >= 0) { contentType = contentType.substring(0, semi); } return OAuth.ContentType.URL_ENCODED.equalsIgnoreCase(contentType.trim()); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testIsFormEncoded() throws Exception { String anotherContentType = "text/html; charset=ISO-8859-4"; String urlEncodedType = "application/x-www-form-urlencoded; charset=UTF-8"; Boolean falseExpected = OAuthUtils.isFormEncoded(anotherContentType); Boolean trueExpected = OAuthUtils.isFormEncoded(urlEncodedType); assertEquals(false, falseExpected); assertEquals(true, trueExpected); } |
### Question:
OAuthUtils { public static String decodePercent(String s) { try { return URLDecoder.decode(s, ENCODING); } catch (java.io.UnsupportedEncodingException wow) { throw new RuntimeException(wow.getMessage(), wow); } } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testDecodePercent() throws Exception { String encoded = "It%20is%20sunny%20today%2C%20spring%20is%20coming!%3A)"; String decoded = OAuthUtils.decodePercent(encoded); assertEquals("It is sunny today, spring is coming!:)", decoded); } |
### Question:
OAuthUtils { public static String percentEncode(String s) { if (s == null) { return ""; } try { return URLEncoder.encode(s, ENCODING) .replace("+", "%20").replace("*", "%2A") .replace("%7E", "~"); } catch (UnsupportedEncodingException wow) { throw new RuntimeException(wow.getMessage(), wow); } } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testPercentEncode() throws Exception { String decoded = "some!@#%weird\"value1"; String encoded = OAuthUtils.percentEncode(decoded); assertEquals("some%21%40%23%25weird%22value1", encoded); } |
### Question:
OAuthUtils { public static <T> T instantiateClass(Class<T> clazz) throws OAuthSystemException { return instantiateClassWithParameters(clazz, null, null); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testInstantiateClass() throws Exception { StringBuilder builder = OAuthUtils.instantiateClass(StringBuilder.class); assertNotNull(builder); } |
### Question:
OAuthUtils { public static <T> T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes, Object[] paramValues) throws OAuthSystemException { try { if (paramsTypes != null && paramValues != null) { if (!(paramsTypes.length == paramValues.length)) { throw new IllegalArgumentException("Number of types and values must be equal"); } if (paramsTypes.length == 0 && paramValues.length == 0) { return clazz.newInstance(); } Constructor<T> clazzConstructor = clazz.getConstructor(paramsTypes); return clazzConstructor.newInstance(paramValues); } return clazz.newInstance(); } catch (NoSuchMethodException e) { throw new OAuthSystemException(e); } catch (InstantiationException e) { throw new OAuthSystemException(e); } catch (IllegalAccessException e) { throw new OAuthSystemException(e); } catch (InvocationTargetException e) { throw new OAuthSystemException(e); } } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testInstantiateClassWithParameters() throws Exception { StringBuilder builder = OAuthUtils.instantiateClassWithParameters(StringBuilder.class, new Class[]{String.class}, new Object[]{"something"}); assertNotNull(builder); assertEquals("something", builder.toString()); } |
### Question:
OAuthUtils { public static String getAuthHeaderField(String authHeader) { if (authHeader != null) { Matcher m = OAUTH_HEADER.matcher(authHeader); if (m.matches()) { if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) { return m.group(2); } } } return null; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testGetAuthHeaderField() throws Exception { String token = OAuthUtils.getAuthHeaderField("Bearer 312ewqdsad"); assertEquals("312ewqdsad", token); } |
### Question:
OAuthUtils { public static Map<String, String> decodeOAuthHeader(String header) { Map<String, String> headerValues = new HashMap<String, String>(); if (header != null) { Matcher m = OAUTH_HEADER.matcher(header); if (m.matches()) { if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) { for (String nvp : m.group(2).split("\\s*,\\s*")) { m = NVP.matcher(nvp); if (m.matches()) { String name = decodePercent(m.group(1)); String value = decodePercent(m.group(2)); headerValues.put(name, value); } } } } } return headerValues; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testDecodeOAuthHeader() throws Exception { Map<String, String> parameters = OAuthUtils.decodeOAuthHeader("Bearer realm=\"example\""); Map<String, String> expected = new HashMap<String, String>(); expected.put("realm", "example"); assertEquals(expected, parameters); } |
### Question:
OAuthUtils { public static String encodeOAuthHeader(Map<String, Object> entries) { StringBuffer sb = new StringBuffer(); sb.append(OAuth.OAUTH_HEADER_NAME).append(" "); if (entries.get("realm") != null) { String value = String.valueOf(entries.get("realm")); if (!OAuthUtils.isEmpty(value)) { sb.append("realm=\""); sb.append(value); sb.append("\","); } entries.remove("realm"); } for (Map.Entry<String, Object> entry : entries.entrySet()) { String value = entry.getValue() == null? null: String.valueOf(entry.getValue()); if (!OAuthUtils.isEmpty(entry.getKey()) && !OAuthUtils.isEmpty(value)) { sb.append(entry.getKey()); sb.append("=\""); sb.append(value); sb.append("\","); } } return sb.substring(0, sb.length() - 1); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testEncodeOAuthHeader() throws Exception { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("realm", "example"); String header = OAuthUtils.encodeOAuthHeader(parameters); assertEquals("Bearer realm=\"example\"", header); }
@Test public void testEncodeOAuthHeaderWithError() throws Exception { Map<String, Object> entries = new HashMap<String, Object>(); entries.put("realm", "Some Example Realm"); entries.put("error", "invalid_token"); String header = OAuthUtils.encodeOAuthHeader(entries); assertEquals("Bearer realm=\"Some Example Realm\",error=\"invalid_token\"", header); } |
### Question:
OAuthUtils { public static String encodeAuthorizationBearerHeader(Map<String, Object> entries) { StringBuffer sb = new StringBuffer(); sb.append(OAuth.OAUTH_HEADER_NAME).append(" "); for (Map.Entry<String, Object> entry : entries.entrySet()) { String value = entry.getValue() == null? null: String.valueOf(entry.getValue()); if (!OAuthUtils.isEmpty(entry.getKey()) && !OAuthUtils.isEmpty(value)) { sb.append(value); } } return sb.toString(); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testEncodeAuthorizationBearerHeader() throws Exception { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("accessToken", "mF_9.B5f-4.1JqM"); String header = OAuthUtils.encodeAuthorizationBearerHeader(parameters); assertEquals("Bearer mF_9.B5f-4.1JqM", header); } |
### Question:
OAuthUtils { private static boolean isEmpty(Set<String> missingParams) { if (missingParams == null || missingParams.size() == 0) { return true; } return false; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testIsEmpty() throws Exception { Boolean trueExpected = OAuthUtils.isEmpty(""); Boolean trueExpected2 = OAuthUtils.isEmpty(null); Boolean falseExpected = OAuthUtils.isEmpty("."); assertEquals(true, trueExpected); assertEquals(true, trueExpected2); assertEquals(false, falseExpected); } |
### Question:
OAuthUtils { public static boolean hasEmptyValues(String[] array) { if (array == null || array.length == 0) { return true; } for (String s : array) { if (isEmpty(s)) { return true; } } return false; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHasEmptyValues() throws Exception { Boolean trueExpected = OAuthUtils.hasEmptyValues(new String[]{"", "dsadas"}); Boolean trueExpected2 = OAuthUtils.hasEmptyValues(new String[]{null, "dsadas"}); Boolean trueExpected3 = OAuthUtils.hasEmptyValues(new String[]{}); Boolean falseExpected = OAuthUtils.hasEmptyValues(new String[]{"qwerty", "dsadas"}); assertEquals(true, trueExpected); assertEquals(true, trueExpected2); assertEquals(true, trueExpected3); assertEquals(false, falseExpected); } |
### Question:
OAuthUtils { public static String getAuthzMethod(String header) { if (header != null) { Matcher m = OAUTH_HEADER.matcher(header); if (m.matches()) { return m.group(1); } } return null; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testGetAuthzMethod() throws Exception { String authzMethod = OAuthUtils.getAuthzMethod("Basic dXNlcjpwYXNzd29yZA=="); assertEquals("Basic", authzMethod); } |
### Question:
OAuthUtils { public static Set<String> decodeScopes(String s) { Set<String> scopes = new HashSet<String>(); if (!OAuthUtils.isEmpty(s)) { StringTokenizer tokenizer = new StringTokenizer(s, " "); while (tokenizer.hasMoreElements()) { scopes.add(tokenizer.nextToken()); } } return scopes; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testDecodeScopes() throws Exception { Set<String> expected = new HashSet<String>(); expected.add("email"); expected.add("full_profile"); Set<String> scopes = OAuthUtils.decodeScopes("email full_profile"); assertEquals(expected, scopes); } |
### Question:
OAuthUtils { public static String encodeScopes(Set<String> s) { StringBuffer scopes = new StringBuffer(); for (String scope : s) { scopes.append(scope).append(" "); } return scopes.toString().trim(); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testEncodeScopes() throws Exception { Set<String> actual = new HashSet<String>(); actual.add("photo"); actual.add("birth_date"); String actualString = OAuthUtils.encodeScopes(actual); assertEquals("birth_date photo", actualString); } |
### Question:
OAuthUtils { public static boolean isMultipart(HttpServletRequest request) { if (!"post".equals(request.getMethod().toLowerCase())) { return false; } String contentType = request.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase().startsWith(MULTIPART)) { return true; } return false; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testIsMultipart() throws Exception { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn("multipart/form-data"); expect(request.getMethod()).andStubReturn("POST"); replay(request); Boolean actual = OAuthUtils.isMultipart(request); assertEquals(true, actual); verify(request); request = createMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn("multipart/form-data"); expect(request.getMethod()).andStubReturn("GET"); replay(request); actual = OAuthUtils.isMultipart(request); assertEquals(false, actual); request = createMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn("application/json"); expect(request.getMethod()).andStubReturn("POST"); replay(request); actual = OAuthUtils.isMultipart(request); assertEquals(false, actual); } |
### Question:
OAuthUtils { public static boolean hasContentType(String requestContentType, String requiredContentType) { if (OAuthUtils.isEmpty(requiredContentType) || OAuthUtils.isEmpty(requestContentType)) { return false; } StringTokenizer tokenizer = new StringTokenizer(requestContentType, ";"); while (tokenizer.hasMoreTokens()) { if (requiredContentType.equals(tokenizer.nextToken())) { return true; } } return false; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHasContentType() throws Exception { Boolean falseExpected = OAuthUtils.hasContentType("application/x-www-form-urlencoded; charset=UTF-8", "application/json"); Boolean trueExpected = OAuthUtils.hasContentType("application/json; charset=UTF-8", "application/json"); assertEquals(false, falseExpected); assertEquals(true, trueExpected); } |
### Question:
OAuthUtils { public static String[] decodeClientAuthenticationHeader(String authenticationHeader) { if (isEmpty(authenticationHeader)) { return null; } String[] tokens = authenticationHeader.split(" "); if (tokens.length != 2) { return null; } String authType = tokens[0]; if (!"basic".equalsIgnoreCase(authType)) { return null; } String encodedCreds = tokens[1]; return decodeBase64EncodedCredentials(encodedCreds); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testDecodeValidClientAuthnHeader() throws Exception { String header = "clientId:secret"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); String[] credentials = OAuthUtils.decodeClientAuthenticationHeader(encodedHeader); assertNotNull(credentials); assertEquals("clientId", credentials[0]); assertEquals("secret", credentials[1]); }
@Test public void testDecodeValidClientAuthnHeaderWithColonInPassword() throws Exception { String header = "clientId:sec:re:t"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); String[] credentials = OAuthUtils.decodeClientAuthenticationHeader(encodedHeader); assertNotNull(credentials); assertEquals("clientId", credentials[0]); assertEquals("sec:re:t", credentials[1]); }
@Test public void testDecodeEmptyClientAuthnHeader() throws Exception { assertNull(OAuthUtils.decodeClientAuthenticationHeader(null)); assertNull(OAuthUtils.decodeClientAuthenticationHeader("")); }
@Test public void testDecodeInvalidClientAuthnHeader() throws Exception { assertNull(OAuthUtils.decodeClientAuthenticationHeader(BASIC_PREFIX)); assertNull(OAuthUtils.decodeClientAuthenticationHeader("invalid_header")); assertNull(OAuthUtils.decodeClientAuthenticationHeader("Authorization dXNlcm5hbWU6cGFzc3dvcmQ=")); }
@Test public void testDecodeClientAuthnHeaderNoClientIdOrSecret() throws Exception { String header = ":"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); assertNull(OAuthUtils.decodeClientAuthenticationHeader(encodedHeader)); }
@Test public void testDecodeClientAuthnHeaderNoClientId() throws Exception { String header = ":secret"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); assertNull(OAuthUtils.decodeClientAuthenticationHeader(encodedHeader)); }
@Test public void testDecodeClientAuthnHeaderNoSecret() throws Exception { String header = "clientId:"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); assertNull(OAuthUtils.decodeClientAuthenticationHeader(encodedHeader)); }
@Test public void testDecodeClientAuthnHeaderNoSeparator() throws Exception { String header = "clientId"; String encodedHeader = BASIC_PREFIX + encodeHeader(header); assertNull(OAuthUtils.decodeClientAuthenticationHeader(encodedHeader)); } |
### Question:
JSONBodyParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String json = null; try { json = JSONUtils.buildJSON(params); message.setBody(json); return message; } catch (Throwable e) { throw new OAuthSystemException(e); } } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new JSONBodyParametersApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String msgBody = message.getBody(); Map<String, Object> map = JSONUtils.parseJSON(msgBody); assertEquals(3600L, map.get(OAuth.OAUTH_EXPIRES_IN)); assertEquals("token_authz", map.get(OAuth.OAUTH_ACCESS_TOKEN)); assertEquals("code_", map.get(OAuth.OAUTH_CODE)); assertEquals("read", map.get(OAuth.OAUTH_SCOPE)); assertEquals("state", map.get(OAuth.OAUTH_STATE)); assertNull(map.get("empty_param")); assertNull(map.get("null_param")); assertNull(map.get("")); assertNull(map.get(null)); } |
### Question:
BodyURLEncodedParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String body = OAuthUtils.format(params.entrySet(), "UTF-8"); message.setBody(body); return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new BodyURLEncodedParametersApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String body = message.getBody(); Assert.assertTrue(body.contains("3600")); Assert.assertTrue(body.contains("token_authz")); Assert.assertTrue(body.contains("code_")); Assert.assertTrue(body.contains("read")); Assert.assertTrue(body.contains("state")); Assert.assertFalse(body.contains("empty_param")); Assert.assertFalse(body.contains("null_param")); } |
### Question:
WWWAuthHeaderParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String header = OAuthUtils.encodeOAuthHeader(params); message.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, header); return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { Map<String, Object> params = new HashMap<String, Object>(); params.put("error", "invalid_token"); params.put("error_uri", "http: params.put("scope", "s1 s2 s3"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthResponse res = OAuthResponse.status(200).location("").buildQueryMessage(); OAuthParametersApplier applier = new WWWAuthHeaderParametersApplier(); res = (OAuthResponse)applier.applyOAuthParameters(res, params); assertNotNull(res); String header = res.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE); assertNotNull(header); assertEquals(OAuth.OAUTH_HEADER_NAME + " scope=\"s1 s2 s3\",error=\"invalid_token\",error_uri=\"http: header); } |
### Question:
FragmentParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String messageUrl = message.getLocationUri(); if (messageUrl != null) { StringBuilder url = new StringBuilder(messageUrl); if (params.containsKey(OAuth.OAUTH_REFRESH_TOKEN)) { params.remove(OAuth.OAUTH_REFRESH_TOKEN); } String fragmentQuery = OAuthUtils.format(params.entrySet(), "UTF-8"); if (!OAuthUtils.isEmpty(fragmentQuery)) { if (params.size() > 0) { url.append("#").append(fragmentQuery); } } message.setLocationUri(url.toString()); } return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new FragmentParametersApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put(OAuth.OAUTH_REFRESH_TOKEN, "token_refresh"); params.put("empty_param", ""); params.put("null_param", null); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String locationURI = message.getLocationUri(); Assert.assertTrue(locationURI.contains("3600")); Assert.assertTrue(locationURI.contains("token_authz")); Assert.assertTrue(locationURI.contains("code_")); Assert.assertTrue(locationURI.contains("read")); Assert.assertTrue(locationURI.contains("state")); Assert.assertFalse(locationURI.contains("token_refresh")); Assert.assertFalse(locationURI.contains("empty_param")); Assert.assertFalse(locationURI.contains("null_param")); } |
### Question:
QueryParameterApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) { String messageUrl = message.getLocationUri(); if (messageUrl != null) { boolean containsQuestionMark = messageUrl.contains("?"); StringBuffer url = new StringBuffer(messageUrl); StringBuffer query = new StringBuffer(OAuthUtils.format(params.entrySet(), "UTF-8")); if (!OAuthUtils.isEmpty(query.toString())) { if (containsQuestionMark) { url.append("&").append(query); } else { url.append("?").append(query); } } message.setLocationUri(url.toString()); } return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new QueryParameterApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String locationURI = message.getLocationUri(); Assert.assertTrue(locationURI.contains("3600")); Assert.assertTrue(locationURI.contains("token_authz")); Assert.assertTrue(locationURI.contains("code_")); Assert.assertTrue(locationURI.contains("read")); Assert.assertTrue(locationURI.contains("state")); Assert.assertTrue(!locationURI.contains("empty_param")); Assert.assertTrue(!locationURI.contains("null_param")); } |
### Question:
OAuthResourceResponse extends OAuthClientResponse { public InputStream getBodyAsInputStream() { if (bodyRetrieved && inputStream == null) { throw new IllegalStateException("Cannot call getBodyAsInputStream() after getBody()"); } bodyRetrieved = true; return inputStream; } OAuthResourceResponse(); String getBody(); int getResponseCode(); String getContentType(); Map<String, List<String>> getHeaders(); InputStream getBodyAsInputStream(); }### Answer:
@Test public void allowBinaryResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(BINARY); final byte[] bytes = IOUtils.toByteArray(resp.getBodyAsInputStream()); assertArrayEquals(BINARY, bytes); }
@Test public void allowStringAsBinaryResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(STRING_BYTES); final byte[] bytes = IOUtils.toByteArray(resp.getBodyAsInputStream()); assertArrayEquals(STRING_BYTES, bytes); } |
### Question:
OAuthResourceResponse extends OAuthClientResponse { public String getBody() { if (bodyRetrieved && body == null) { throw new IllegalStateException("Cannot call getBody() after getBodyAsInputStream()"); } if (body == null) { try { body = OAuthUtils.saveStreamAsString(getBodyAsInputStream()); inputStream = null; } catch (IOException e) { LOG.error("Failed to convert InputStream to String", e); } } return body; } OAuthResourceResponse(); String getBody(); int getResponseCode(); String getContentType(); Map<String, List<String>> getHeaders(); InputStream getBodyAsInputStream(); }### Answer:
@Test public void allowStringResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(STRING_BYTES); assertEquals("getBody() should return correct string", STRING, resp.getBody()); } |
### Question:
OAuthClientResponseFactory { public static OAuthClientResponse createGitHubTokenResponse(String body, String contentType, int responseCode) throws OAuthProblemException { GitHubTokenResponse resp = new GitHubTokenResponse(); resp.init(body, contentType, responseCode); return resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType,
int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType,
int responseCode); static T createCustomResponse(String body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); static T createCustomResponse(InputStream body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); }### Answer:
@Test public void testCreateGitHubTokenResponse() throws Exception { OAuthClientResponse gitHubTokenResponse = OAuthClientResponseFactory .createGitHubTokenResponse("access_token=123", OAuth.ContentType.URL_ENCODED, 200); assertNotNull(gitHubTokenResponse); } |
### Question:
OAuthClientResponseFactory { public static OAuthClientResponse createJSONTokenResponse(String body, String contentType, int responseCode) throws OAuthProblemException { OAuthJSONAccessTokenResponse resp = new OAuthJSONAccessTokenResponse(); resp.init(body, contentType, responseCode); return resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType,
int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType,
int responseCode); static T createCustomResponse(String body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); static T createCustomResponse(InputStream body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); }### Answer:
@Test public void testCreateJSONTokenResponse() throws Exception { OAuthClientResponse jsonTokenResponse = OAuthClientResponseFactory .createJSONTokenResponse("{\"access_token\":\"123\"}", OAuth.ContentType.JSON, 200); assertNotNull(jsonTokenResponse); } |
### Question:
OAuthClientResponseFactory { public static <T extends OAuthClientResponse> T createCustomResponse(String body, String contentType, int responseCode, Map<String, List<String>> headers, Class<T> clazz) throws OAuthSystemException, OAuthProblemException { OAuthClientResponse resp = OAuthUtils .instantiateClassWithParameters(clazz, null, null); resp.init(body, contentType, responseCode, headers); return (T) resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType,
int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType,
int responseCode); static T createCustomResponse(String body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); static T createCustomResponse(InputStream body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); }### Answer:
@Test public void testCreateCustomResponse() throws Exception { } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public String getAccessToken() { return getParam(OAuth.OAUTH_ACCESS_TOKEN); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testGetAccessToken() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.ACCESS_TOKEN, r.getAccessToken()); try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertNotNull(e.getError()); } } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public String getTokenType() { return getParam(OAuth.OAUTH_TOKEN_TYPE); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testGetTokenType() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.TOKEN_TYPE, r.getTokenType()); try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertNotNull(e.getError()); } } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { @Override public Long getExpiresIn() { String value = getParam(OAuth.OAUTH_EXPIRES_IN); return value == null? null: Long.valueOf(value); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testGetExpiresIn() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.EXPIRES_IN, r.getExpiresIn()); initAndAssertError(r); } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { public String getScope() { return getParam(OAuth.OAUTH_SCOPE); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testGetScope() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.SCOPE, r.getScope()); initAndAssertError(r); } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { public String getRefreshToken() { return getParam(OAuth.OAUTH_REFRESH_TOKEN); } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testGetRefreshToken() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } Assert.assertEquals(TestUtils.REFRESH_TOKEN, r.getRefreshToken()); initAndAssertError(r); } |
### Question:
OAuthJSONAccessTokenResponse extends OAuthAccessTokenResponse { protected void setBody(String body) throws OAuthProblemException { try { this.body = body; parameters = JSONUtils.parseJSON(body); } catch (Throwable e) { throw OAuthProblemException.error(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE, "Invalid response! Response body is not " + OAuth.ContentType.JSON + " encoded"); } } OAuthJSONAccessTokenResponse(); @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); String getScope(); OAuthToken getOAuthToken(); String getRefreshToken(); }### Answer:
@Test public void testSetBody() throws Exception { OAuthJSONAccessTokenResponse r = null; try { r = new OAuthJSONAccessTokenResponse(); r.init(TestUtils.VALID_JSON_RESPONSE, OAuth.ContentType.JSON, 200); } catch (OAuthProblemException e) { fail("Exception not expected"); } String accessToken = r.getAccessToken(); Long expiresIn = r.getExpiresIn(); Assert.assertEquals(TestUtils.EXPIRES_IN, expiresIn); Assert.assertEquals(TestUtils.ACCESS_TOKEN, accessToken); try { new OAuthJSONAccessTokenResponse(); r.init(TestUtils.ERROR_JSON_BODY, OAuth.ContentType.JSON, 200); fail("Exception expected"); } catch (OAuthProblemException e) { Assert.assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, e.getError()); } } |
### Question:
GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getAccessToken() { return getParam(OAuth.OAUTH_ACCESS_TOKEN); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer:
@Test public void testGetAccessToken() throws Exception { } |
### Question:
GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public Long getExpiresIn() { String value = getParam(OAuth.OAUTH_EXPIRES_IN); return value == null? null: Long.valueOf(value); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer:
@Test public void testGetExpiresIn() throws Exception { } |
### Question:
GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getRefreshToken() { return getParam(OAuth.OAUTH_REFRESH_TOKEN); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer:
@Test public void testGetRefreshToken() throws Exception { } |
### Question:
GitHubTokenResponse extends OAuthAccessTokenResponse { @Override public String getScope() { return getParam(OAuth.OAUTH_SCOPE); } @Override String getAccessToken(); @Override String getTokenType(); @Override Long getExpiresIn(); @Override String getRefreshToken(); @Override String getScope(); @Override OAuthToken getOAuthToken(); }### Answer:
@Test public void testGetScope() throws Exception { } |
### Question:
OpenIdConnectResponse extends OAuthJSONAccessTokenResponse { public boolean checkId(String issuer, String audience) { if (idToken.getClaimsSet().getIssuer().equals(issuer) && idToken.getClaimsSet().getAudience().equals(audience) && idToken.getClaimsSet().getExpirationTime() < System .currentTimeMillis()) { return true; } return false; } final JWT getIdToken(); boolean checkId(String issuer, String audience); }### Answer:
@Test public void testCheckId() throws NoSuchFieldException{ JWT idToken = new JWTReader().read(JWT); OpenIdConnectResponse openIdConnectResponse= new OpenIdConnectResponse(); PrivateAccessor.setField(openIdConnectResponse, "idToken", idToken); assertTrue(openIdConnectResponse.checkId("accounts.google.com", "788732372078.apps.googleusercontent.com")); assertFalse(openIdConnectResponse.checkId("wrongaccounts.google.com", "788732372078.apps.googleusercontent.com")); assertFalse(openIdConnectResponse.checkId("wrongaccounts.google.com", "notexists788732372078.apps.googleusercontent.com")); } |
### Question:
MessageDecryptVerifier { public static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts) { if (isPartEncryptedOrSigned(part)) { return part; } Part foundPart; foundPart = findPrimaryPartInAlternative(part); if (foundPart != null) { return foundPart; } foundPart = findPrimaryPartInMixed(part, outputExtraParts); if (foundPart != null) { return foundPart; } return null; } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findEncryptedParts(Part startPart); static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPgpMimeEncryptedOrSignedPart(Part part); static boolean isSMimeEncryptedOrSignedPart(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer:
@Test public void findPrimaryCryptoPart_withSimplePgpInline() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); Message message = new MimeMessage(); MimeMessageHelper.setBody(message, new TextBody(PGP_INLINE_DATA)); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertSame(message, cryptoPart); }
@Test public void findPrimaryCryptoPart_withMultipartAlternativeContainingPgpInline() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); BodyPart pgpInlinePart = bodypart("text/plain", PGP_INLINE_DATA); Message message = messageFromBody( multipart("alternative", pgpInlinePart, bodypart("text/html") ) ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertSame(pgpInlinePart, cryptoPart); }
@Test public void findPrimaryCryptoPart_withMultipartMixedContainingPgpInline() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); BodyPart pgpInlinePart = bodypart("text/plain", PGP_INLINE_DATA); Message message = messageFromBody( multipart("mixed", pgpInlinePart, bodypart("application/octet-stream") ) ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertSame(pgpInlinePart, cryptoPart); }
@Test public void findPrimaryCryptoPart_withMultipartMixedContainingMultipartAlternativeContainingPgpInline() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); BodyPart pgpInlinePart = bodypart("text/plain", PGP_INLINE_DATA); Message message = messageFromBody( multipart("mixed", multipart("alternative", pgpInlinePart, bodypart("text/html") ), bodypart("application/octet-stream") ) ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertSame(pgpInlinePart, cryptoPart); }
@Test public void findPrimaryCryptoPart_withEmptyMultipartAlternative_shouldReturnNull() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); Message message = messageFromBody( multipart("alternative") ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertNull(cryptoPart); }
@Test public void findPrimaryCryptoPart_withEmptyMultipartMixed_shouldReturnNull() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); Message message = messageFromBody( multipart("mixed") ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertNull(cryptoPart); }
@Test public void findPrimaryCryptoPart_withEmptyMultipartAlternativeInsideMultipartMixed_shouldReturnNull() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); Message message = messageFromBody( multipart("mixed", multipart("alternative") ) ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertNull(cryptoPart); } |
### Question:
BitcoinUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = BITCOIN_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String bitcoinUri = matcher.group(); outputBuffer.append("<a href=\"") .append(bitcoinUri) .append("\">") .append(bitcoinUri) .append("</a>"); return matcher.end(); } @Override int linkifyUri(String text, int startPos, StringBuffer outputBuffer); }### Answer:
@Test public void uriInMiddleOfInput() throws Exception { String prefix = "prefix "; String uri = "bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2"; String text = prefix + uri; parser.linkifyUri(text, prefix.length(), outputBuffer); assertLinkOnly(uri, outputBuffer); } |
### Question:
MessageBuilder { final public void buildAsync(Callback callback) { synchronized (callbackLock) { asyncCallback = callback; queuedMimeMessage = null; queuedException = null; queuedPendingIntent = null; } new AsyncTask<Void,Void,Void>() { @Override protected Void doInBackground(Void... params) { buildMessageInternal(); return null; } @Override protected void onPostExecute(Void aVoid) { deliverResult(); } }.execute(); } protected MessageBuilder(Context context, MessageIdGenerator messageIdGenerator, BoundaryGenerator boundaryGenerator); MessageBuilder setSubject(String subject); MessageBuilder setSentDate(Date sentDate); MessageBuilder setHideTimeZone(boolean hideTimeZone); MessageBuilder setTo(List<Address> to); MessageBuilder setCc(List<Address> cc); MessageBuilder setBcc(List<Address> bcc); MessageBuilder setInReplyTo(String inReplyTo); MessageBuilder setReferences(String references); MessageBuilder setRequestReadReceipt(boolean requestReadReceipt); MessageBuilder setIdentity(Identity identity); MessageBuilder setMessageFormat(SimpleMessageFormat messageFormat); MessageBuilder setText(String text); MessageBuilder setAttachments(List<Attachment> attachments); MessageBuilder setSignature(String signature); MessageBuilder setQuoteStyle(QuoteStyle quoteStyle); MessageBuilder setQuotedTextMode(QuotedTextMode quotedTextMode); MessageBuilder setQuotedText(String quotedText); MessageBuilder setQuotedHtmlContent(InsertableHtmlContent quotedHtmlContent); MessageBuilder setReplyAfterQuote(boolean isReplyAfterQuote); MessageBuilder setSignatureBeforeQuotedText(boolean isSignatureBeforeQuotedText); MessageBuilder setIdentityChanged(boolean identityChanged); MessageBuilder setSignatureChanged(boolean signatureChanged); MessageBuilder setCursorPosition(int cursorPosition); MessageBuilder setMessageReference(MessageReference messageReference); MessageBuilder setDraft(boolean isDraft); MessageBuilder setIsPgpInlineEnabled(boolean isPgpInlineEnabled); boolean isDraft(); final void buildAsync(Callback callback); final void onActivityResult(final int requestCode, int resultCode, final Intent data, Callback callback); final void detachCallback(); final void reattachCallback(Callback callback); }### Answer:
@Test public void build_shouldSucceed() throws Exception { MessageBuilder messageBuilder = createSimpleMessageBuilder(); messageBuilder.buildAsync(callback); MimeMessage message = getMessageFromCallback(); assertEquals("text/plain", message.getMimeType()); assertEquals(TEST_SUBJECT, message.getSubject()); assertEquals(TEST_IDENTITY_ADDRESS, message.getFrom()[0]); assertArrayEquals(TEST_TO, message.getRecipients(RecipientType.TO)); assertArrayEquals(TEST_CC, message.getRecipients(RecipientType.CC)); assertArrayEquals(TEST_BCC, message.getRecipients(RecipientType.BCC)); assertEquals(MESSAGE_HEADERS + MESSAGE_CONTENT, getMessageContents(message)); }
@Test public void build_usingHtmlFormat_shouldUseMultipartAlternativeInCorrectOrder() { MessageBuilder messageBuilder = createHtmlMessageBuilder(); messageBuilder.buildAsync(callback); MimeMessage message = getMessageFromCallback(); assertEquals(MimeMultipart.class, message.getBody().getClass()); assertEquals("multipart/alternative", ((MimeMultipart) message.getBody()).getMimeType()); List<BodyPart> parts = ((MimeMultipart) message.getBody()).getBodyParts(); assertEquals("text/plain", parts.get(0).getMimeType()); assertEquals("text/html", parts.get(1).getMimeType()); } |
### Question:
AttachmentInfoExtractor { @WorkerThread public AttachmentViewInfo extractAttachmentInfo(Part part) throws MessagingException { Uri uri; long size; boolean isContentAvailable; if (part instanceof LocalPart) { LocalPart localPart = (LocalPart) part; String accountUuid = localPart.getAccountUuid(); long messagePartId = localPart.getPartId(); size = localPart.getSize(); isContentAvailable = part.getBody() != null; uri = AttachmentProvider.getAttachmentUri(accountUuid, messagePartId); } else if (part instanceof LocalMessage) { LocalMessage localMessage = (LocalMessage) part; String accountUuid = localMessage.getAccount().getUuid(); long messagePartId = localMessage.getMessagePartId(); size = localMessage.getSize(); isContentAvailable = part.getBody() != null; uri = AttachmentProvider.getAttachmentUri(accountUuid, messagePartId); } else { Body body = part.getBody(); if (body instanceof DeferredFileBody) { DeferredFileBody decryptedTempFileBody = (DeferredFileBody) body; size = decryptedTempFileBody.getSize(); uri = getDecryptedFileProviderUri(decryptedTempFileBody, part.getMimeType()); isContentAvailable = true; } else { throw new IllegalArgumentException("Unsupported part type provided"); } } return extractAttachmentInfo(part, uri, size, isContentAvailable); } @VisibleForTesting AttachmentInfoExtractor(Context context); static AttachmentInfoExtractor getInstance(); @WorkerThread List<AttachmentViewInfo> extractAttachmentInfoForView(List<Part> attachmentParts); @WorkerThread AttachmentViewInfo extractAttachmentInfo(Part part); AttachmentViewInfo extractAttachmentInfoForDatabase(Part part); }### Answer:
@Test(expected = IllegalArgumentException.class) public void extractInfo__withGenericPart_shouldThrow() throws Exception { Part part = mock(Part.class); attachmentInfoExtractor.extractAttachmentInfo(part); }
@Test public void extractInfo__fromLocalBodyPart__shouldReturnProvidedValues() throws Exception { LocalBodyPart part = new LocalBodyPart(TEST_ACCOUNT_UUID, null, TEST_ID, TEST_SIZE); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, TEST_MIME_TYPE); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfo(part); assertEquals(AttachmentProvider.getAttachmentUri(TEST_ACCOUNT_UUID, TEST_ID), attachmentViewInfo.internalUri); assertEquals(TEST_SIZE, attachmentViewInfo.size); assertEquals(TEST_MIME_TYPE, attachmentViewInfo.mimeType); }
@Test public void extractInfo__withDeferredFileBody() throws Exception { attachmentInfoExtractor = new AttachmentInfoExtractor(context) { @Nullable @Override protected Uri getDecryptedFileProviderUri(DeferredFileBody decryptedTempFileBody, String mimeType) { return TEST_URI; } }; DeferredFileBody body = mock(DeferredFileBody.class); when(body.getSize()).thenReturn(TEST_SIZE); MimeBodyPart part = new MimeBodyPart(); part.setBody(body); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, TEST_MIME_TYPE); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfo(part); assertEquals(TEST_URI, attachmentViewInfo.internalUri); assertEquals(TEST_SIZE, attachmentViewInfo.size); assertEquals(TEST_MIME_TYPE, attachmentViewInfo.mimeType); assertFalse(attachmentViewInfo.inlineAttachment); assertTrue(attachmentViewInfo.isContentAvailable()); } |
### Question:
MessagePreviewCreator { public PreviewResult createPreview(@NonNull Message message) { if (encryptionDetector.isEncrypted(message)) { return PreviewResult.encrypted(); } return extractText(message); } MessagePreviewCreator(TextPartFinder textPartFinder, PreviewTextExtractor previewTextExtractor,
EncryptionDetector encryptionDetector); static MessagePreviewCreator newInstance(); PreviewResult createPreview(@NonNull Message message); }### Answer:
@Test public void createPreview_withEncryptedMessage() throws Exception { Message message = createDummyMessage(); when(encryptionDetector.isEncrypted(message)).thenReturn(true); PreviewResult result = previewCreator.createPreview(message); assertFalse(result.isPreviewTextAvailable()); assertEquals(PreviewType.ENCRYPTED, result.getPreviewType()); verifyNoMoreInteractions(textPartFinder); verifyNoMoreInteractions(previewTextExtractor); }
@Test public void createPreview_withoutTextPart() throws Exception { Message message = createDummyMessage(); when(encryptionDetector.isEncrypted(message)).thenReturn(false); when(textPartFinder.findFirstTextPart(message)).thenReturn(null); PreviewResult result = previewCreator.createPreview(message); assertFalse(result.isPreviewTextAvailable()); assertEquals(PreviewType.NONE, result.getPreviewType()); verifyNoMoreInteractions(previewTextExtractor); }
@Test public void createPreview_withEmptyTextPart() throws Exception { Message message = createDummyMessage(); Part textPart = createEmptyPart("text/plain"); when(encryptionDetector.isEncrypted(message)).thenReturn(false); when(textPartFinder.findFirstTextPart(message)).thenReturn(textPart); PreviewResult result = previewCreator.createPreview(message); assertFalse(result.isPreviewTextAvailable()); assertEquals(PreviewType.NONE, result.getPreviewType()); verifyNoMoreInteractions(previewTextExtractor); }
@Test public void createPreview_withTextPart() throws Exception { Message message = createDummyMessage(); Part textPart = createTextPart("text/plain"); when(encryptionDetector.isEncrypted(message)).thenReturn(false); when(textPartFinder.findFirstTextPart(message)).thenReturn(textPart); when(previewTextExtractor.extractPreview(textPart)).thenReturn("expected"); PreviewResult result = previewCreator.createPreview(message); assertTrue(result.isPreviewTextAvailable()); assertEquals(PreviewType.TEXT, result.getPreviewType()); assertEquals("expected", result.getPreviewText()); }
@Test public void createPreview_withPreviewTextExtractorThrowing() throws Exception { Message message = createDummyMessage(); Part textPart = createTextPart("text/plain"); when(encryptionDetector.isEncrypted(message)).thenReturn(false); when(textPartFinder.findFirstTextPart(message)).thenReturn(textPart); when(previewTextExtractor.extractPreview(textPart)).thenThrow(new PreviewExtractionException("")); PreviewResult result = previewCreator.createPreview(message); assertFalse(result.isPreviewTextAvailable()); assertEquals(PreviewType.ERROR, result.getPreviewType()); } |
### Question:
EncryptionDetector { public boolean isEncrypted(@NonNull Message message) { return isPgpMimeOrSMimeEncrypted(message) || containsInlinePgpEncryptedText(message); } EncryptionDetector(TextPartFinder textPartFinder); boolean isEncrypted(@NonNull Message message); }### Answer:
@Test public void isEncrypted_withTextPlain_shouldReturnFalse() throws Exception { Message message = createTextMessage("text/plain", "plain text"); boolean encrypted = encryptionDetector.isEncrypted(message); assertFalse(encrypted); }
@Test public void isEncrypted_withMultipartEncrypted_shouldReturnTrue() throws Exception { Message message = createMultipartMessage("multipart/encrypted", createPart("application/octet-stream"), createPart("application/octet-stream")); boolean encrypted = encryptionDetector.isEncrypted(message); assertTrue(encrypted); }
@Test public void isEncrypted_withSMimePart_shouldReturnTrue() throws Exception { Message message = createMessage("application/pkcs7-mime"); boolean encrypted = encryptionDetector.isEncrypted(message); assertTrue(encrypted); }
@Test public void isEncrypted_withMultipartMixedContainingSMimePart_shouldReturnTrue() throws Exception { Message message = createMultipartMessage("multipart/mixed", createPart("application/pkcs7-mime"), createPart("text/plain")); boolean encrypted = encryptionDetector.isEncrypted(message); assertTrue(encrypted); }
@Test public void isEncrypted_withInlinePgp_shouldReturnTrue() throws Exception { Message message = createTextMessage("text/plain", "" + "-----BEGIN PGP MESSAGE-----" + CRLF + "some encrypted stuff here" + CRLF + "-----END PGP MESSAGE-----"); when(textPartFinder.findFirstTextPart(message)).thenReturn(message); boolean encrypted = encryptionDetector.isEncrypted(message); assertTrue(encrypted); }
@Test public void isEncrypted_withPlainTextAndPreambleWithInlinePgp_shouldReturnFalse() throws Exception { Message message = createTextMessage("text/plain", "" + "preamble" + CRLF + "-----BEGIN PGP MESSAGE-----" + CRLF + "some encrypted stuff here" + CRLF + "-----END PGP MESSAGE-----" + CRLF + "epilogue"); when(textPartFinder.findFirstTextPart(message)).thenReturn(message); boolean encrypted = encryptionDetector.isEncrypted(message); assertFalse(encrypted); }
@Test public void isEncrypted_withQuotedInlinePgp_shouldReturnFalse() throws Exception { Message message = createTextMessage("text/plain", "" + "good talk!" + CRLF + CRLF + "> -----BEGIN PGP MESSAGE-----" + CRLF + "> some encrypted stuff here" + CRLF + "> -----END PGP MESSAGE-----" + CRLF + CRLF + "-- " + CRLF + "my signature"); when(textPartFinder.findFirstTextPart(message)).thenReturn(message); boolean encrypted = encryptionDetector.isEncrypted(message); assertFalse(encrypted); } |
### Question:
MessageDecryptVerifier { public static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations) { List<Part> signedParts = new ArrayList<>(); Stack<Part> partsToCheck = new Stack<>(); partsToCheck.push(startPart); while (!partsToCheck.isEmpty()) { Part part = partsToCheck.pop(); if (messageCryptoAnnotations.has(part)) { CryptoResultAnnotation resultAnnotation = messageCryptoAnnotations.get(part); MimeBodyPart replacementData = resultAnnotation.getReplacementData(); if (replacementData != null) { part = replacementData; } } Body body = part.getBody(); if (isPartMultipartSigned(part)) { signedParts.add(part); continue; } if (body instanceof Multipart) { Multipart multipart = (Multipart) body; for (int i = multipart.getCount() - 1; i >= 0; i--) { BodyPart bodyPart = multipart.getBodyPart(i); partsToCheck.push(bodyPart); } } } return signedParts; } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findEncryptedParts(Part startPart); static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPgpMimeEncryptedOrSignedPart(Part part); static boolean isSMimeEncryptedOrSignedPart(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer:
@Test public void findSigned__withSimpleMultipartSigned__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageDecryptVerifier.findSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
@Test public void findSigned__withComplexMultipartSigned__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", multipart("mixed", bodypart("text/plain"), bodypart("application/pdf") ), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageDecryptVerifier.findSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageDecryptVerifier.findSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubSignedAndText__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ), bodypart("text/plain") ) ); List<Part> signedParts = MessageDecryptVerifier.findSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubTextAndSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageDecryptVerifier.findSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 1), signedParts.get(0)); } |
### Question:
AccountCreator { public static DeletePolicy getDefaultDeletePolicy(Type type) { switch (type) { case IMAP: { return DeletePolicy.ON_DELETE; } case POP3: { return DeletePolicy.NEVER; } case WebDAV: { return DeletePolicy.ON_DELETE; } case EWS: { return DeletePolicy.ON_DELETE; } case SMTP: { throw new IllegalStateException("Delete policy doesn't apply to SMTP"); } } throw new AssertionError("Unhandled case: " + type); } static DeletePolicy getDefaultDeletePolicy(Type type); static int getDefaultPort(ConnectionSecurity securityType, Type storeType); }### Answer:
@Test public void getDefaultDeletePolicy_withImap_shouldReturn_ON_DELETE() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.IMAP); assertEquals(DeletePolicy.ON_DELETE, result); }
@Test public void getDefaultDeletePolicy_withPop3_shouldReturn_NEVER() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.POP3); assertEquals(DeletePolicy.NEVER, result); }
@Test public void getDefaultDeletePolicy_withWebDav_shouldReturn_ON_DELETE() { DeletePolicy result = AccountCreator.getDefaultDeletePolicy(Type.WebDAV); assertEquals(DeletePolicy.ON_DELETE, result); } |
### Question:
AccountCreator { public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) { switch (securityType) { case NONE: case STARTTLS_REQUIRED: { return storeType.defaultPort; } case SSL_TLS_REQUIRED: { return storeType.defaultTlsPort; } } throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType); } static DeletePolicy getDefaultDeletePolicy(Type type); static int getDefaultPort(ConnectionSecurity securityType, Type storeType); }### Answer:
@Test public void getDefaultPort_withNoConnectionSecurityAndImap_shouldReturnDefaultPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.NONE, Type.IMAP); assertEquals(Type.IMAP.defaultPort, result); }
@Test public void getDefaultPort_withStartTlsAndImap_shouldReturnDefaultPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.STARTTLS_REQUIRED, Type.IMAP); assertEquals(Type.IMAP.defaultPort, result); }
@Test public void getDefaultPort_withTlsAndImap_shouldReturnDefaultTlsPort() { int result = AccountCreator.getDefaultPort(ConnectionSecurity.SSL_TLS_REQUIRED, Type.IMAP); assertEquals(Type.IMAP.defaultTlsPort, result); } |
### Question:
MessageDecryptVerifier { public static boolean isPartPgpInlineEncrypted(@Nullable Part part) { if (part == null) { return false; } if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findEncryptedParts(Part startPart); static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPgpMimeEncryptedOrSignedPart(Part part); static boolean isSMimeEncryptedOrSignedPart(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer:
@Test public void isPgpInlineMethods__withPgpInlineData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP MESSAGE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageDecryptVerifier.isPartPgpInlineEncrypted(message)); }
@Test public void isPartPgpInlineEncrypted__withSignedData__shouldReturnFalse() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertFalse(MessageDecryptVerifier.isPartPgpInlineEncrypted(message)); } |
### Question:
MessageDecryptVerifier { @VisibleForTesting static boolean isPartPgpInlineEncryptedOrSigned(Part part) { if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER) || text.startsWith(PGP_INLINE_SIGNED_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findEncryptedParts(Part startPart); static List<Part> findSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPgpMimeEncryptedOrSignedPart(Part part); static boolean isSMimeEncryptedOrSignedPart(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); }### Answer:
@Test public void isPartPgpInlineEncryptedOrSigned__withSignedData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageDecryptVerifier.isPartPgpInlineEncryptedOrSigned(message)); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { @Override public long getSize() { if (file != null) { return file.length(); } if (data != null) { return data.length; } throw new IllegalStateException("Data must be fully written before it can be read!"); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test public void withShortData__getLength__shouldReturnWrittenLength() throws Exception { writeShortTestData(); assertNull(createdFile); assertEquals(TEST_DATA_SHORT.length, deferredFileBody.getSize()); }
@Test public void withLongData__getLength__shouldReturnWrittenLength() throws Exception { writeLongTestData(); assertNotNull(createdFile); assertEquals(TEST_DATA_LONG.length, deferredFileBody.getSize()); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { @Override public InputStream getInputStream() throws MessagingException { try { if (file != null) { Timber.d("Decrypted data is file-backed."); return new BufferedInputStream(new FileInputStream(file)); } if (data != null) { Timber.d("Decrypted data is memory-backed."); return new ByteArrayInputStream(data); } throw new IllegalStateException("Data must be fully written before it can be read!"); } catch (IOException ioe) { throw new MessagingException("Unable to open body", ioe); } } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test public void withShortData__shouldReturnData() throws Exception { writeShortTestData(); InputStream inputStream = deferredFileBody.getInputStream(); byte[] data = IOUtils.toByteArray(inputStream); assertNull(createdFile); assertArrayEquals(TEST_DATA_SHORT, data); }
@Test public void withLongData__shouldReturnData() throws Exception { writeLongTestData(); InputStream inputStream = deferredFileBody.getInputStream(); byte[] data = IOUtils.toByteArray(inputStream); InputStream fileInputStream = new FileInputStream(createdFile); byte[] dataFromFile = IOUtils.toByteArray(fileInputStream); assertArrayEquals(TEST_DATA_LONG, data); assertArrayEquals(TEST_DATA_LONG, dataFromFile); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { public File getFile() throws IOException { if (file == null) { writeMemoryToFile(); } return file; } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test public void withShortData__getFile__shouldWriteDataToFile() throws Exception { writeShortTestData(); File returnedFile = deferredFileBody.getFile(); InputStream fileInputStream = new FileInputStream(returnedFile); byte[] dataFromFile = IOUtils.toByteArray(fileInputStream); assertSame(createdFile, returnedFile); assertArrayEquals(TEST_DATA_SHORT, dataFromFile); }
@Test public void withLongData__getFile__shouldReturnCreatedFile() throws Exception { writeLongTestData(); File returnedFile = deferredFileBody.getFile(); assertSame(createdFile, returnedFile); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { @Override public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream inputStream = getInputStream(); IOUtils.copy(inputStream, out); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test public void withShortData__writeTo__shouldWriteData() throws Exception { writeShortTestData(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); deferredFileBody.writeTo(baos); assertArrayEquals(TEST_DATA_SHORT, baos.toByteArray()); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { @Override public void setEncoding(String encoding) throws MessagingException { throw new UnsupportedOperationException("Cannot re-encode a DecryptedTempFileBody!"); } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test(expected = UnsupportedOperationException.class) public void setEncoding__shouldThrow() throws Exception { deferredFileBody.setEncoding("anything"); } |
### Question:
DeferredFileBody implements RawDataBody, SizeAware { @Override public String getEncoding() { return encoding; } DeferredFileBody(FileFactory fileFactory, String transferEncoding); @VisibleForTesting DeferredFileBody(int memoryBackedThreshold, FileFactory fileFactory,
String transferEncoding); OutputStream getOutputStream(); @Override InputStream getInputStream(); @Override long getSize(); File getFile(); @Override void setEncoding(String encoding); @Override void writeTo(OutputStream out); @Override String getEncoding(); static final int DEFAULT_MEMORY_BACKED_THRESHOLD; }### Answer:
@Test public void getEncoding__shouldReturnEncoding() throws Exception { assertEquals(TEST_ENCODING, deferredFileBody.getEncoding()); } |
### Question:
StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override public int getVersion() { return LocalStore.DB_VERSION; } StoreSchemaDefinition(LocalStore localStore); @Override int getVersion(); @Override void doDbUpgrade(final SQLiteDatabase db); }### Answer:
@Test public void getVersion_shouldReturnCurrentDatabaseVersion() { int version = storeSchemaDefinition.getVersion(); assertEquals(LocalStore.DB_VERSION, version); } |
### Question:
StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override public void doDbUpgrade(final SQLiteDatabase db) { try { upgradeDatabase(db); } catch (Exception e) { if (BuildConfig.DEBUG) { throw new Error("Exception while upgrading database", e); } Timber.e(e, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); upgradeDatabase(db); } } StoreSchemaDefinition(LocalStore localStore); @Override int getVersion(); @Override void doDbUpgrade(final SQLiteDatabase db); }### Answer:
@Test public void doDbUpgrade_withBadDatabase_shouldThrowInDebugBuild() { if (BuildConfig.DEBUG) { SQLiteDatabase database = SQLiteDatabase.create(null); database.setVersion(29); try { storeSchemaDefinition.doDbUpgrade(database); fail("Expected Error"); } catch (Error e) { assertEquals("Exception while upgrading database", e.getMessage()); } } }
@Test public void doDbUpgrade_withV29() { SQLiteDatabase database = createV29Database(); insertMessageWithSubject(database, "Test Email"); storeSchemaDefinition.doDbUpgrade(database); assertMessageWithSubjectExists(database, "Test Email"); }
@Test public void doDbUpgrade_fromV29_shouldResultInSameTables() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseTablesEquals(newDatabase, upgradedDatabase); }
@Test public void doDbUpgrade_fromV29_shouldResultInSameTriggers() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseTriggersEquals(newDatabase, upgradedDatabase); }
@Test public void doDbUpgrade_fromV29_shouldResultInSameIndexes() { SQLiteDatabase newDatabase = createNewDatabase(); SQLiteDatabase upgradedDatabase = createV29Database(); storeSchemaDefinition.doDbUpgrade(upgradedDatabase); assertDatabaseIndexesEquals(newDatabase, upgradedDatabase); } |
### Question:
MigrationTo60 { static void migratePendingCommands(SQLiteDatabase db) { List<PendingCommand> pendingCommands = new ArrayList<>(); if (columnExists(db, "pending_commands", "arguments")) { for (OldPendingCommand oldPendingCommand : getPendingCommands(db)) { PendingCommand newPendingCommand = migratePendingCommand(oldPendingCommand); pendingCommands.add(newPendingCommand); } db.execSQL("DROP TABLE IF EXISTS pending_commands"); db.execSQL("CREATE TABLE pending_commands (" + "id INTEGER PRIMARY KEY, " + "command TEXT, " + "data TEXT" + ")"); PendingCommandSerializer pendingCommandSerializer = PendingCommandSerializer.getInstance(); for (PendingCommand pendingCommand : pendingCommands) { ContentValues cv = new ContentValues(); cv.put("command", pendingCommand.getCommandName()); cv.put("data", pendingCommandSerializer.serialize(pendingCommand)); db.insert("pending_commands", "command", cv); } } } }### Answer:
@Test public void migratePendingCommands_shouldChangeTableStructure() { SQLiteDatabase database = createV59Table(); MigrationTo60.migratePendingCommands(database); List<String> columns = getColumnList(database, "pending_commands"); assertEquals(asList("id", "command", "data"), columns); }
@Test public void migratePendingCommands_withMultipleRuns_shouldNotThrow() { SQLiteDatabase database = createV59Table(); MigrationTo60.migratePendingCommands(database); MigrationTo60.migratePendingCommands(database); } |
### Question:
AttachmentResolver { @VisibleForTesting static Map<String,Uri> buildCidToAttachmentUriMap(AttachmentInfoExtractor attachmentInfoExtractor, Part rootPart) { HashMap<String,Uri> result = new HashMap<>(); Stack<Part> partsToCheck = new Stack<>(); partsToCheck.push(rootPart); while (!partsToCheck.isEmpty()) { Part part = partsToCheck.pop(); Body body = part.getBody(); if (body instanceof Multipart) { Multipart multipart = (Multipart) body; for (Part bodyPart : multipart.getBodyParts()) { partsToCheck.push(bodyPart); } } else { try { String contentId = part.getContentId(); if (contentId != null) { AttachmentViewInfo attachmentInfo = attachmentInfoExtractor.extractAttachmentInfo(part); result.put(contentId, attachmentInfo.internalUri); } } catch (MessagingException e) { Timber.e(e, "Error extracting attachment info"); } } } return Collections.unmodifiableMap(result); } private AttachmentResolver(Map<String, Uri> contentIdToAttachmentUriMap); @Nullable Uri getAttachmentUriForContentId(String cid); @WorkerThread static AttachmentResolver createFromPart(Part part); }### Answer:
@Test public void buildCidMap__onPartWithNoBody__shouldReturnEmptyMap() throws Exception { Part part = new MimeBodyPart(); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, part); assertTrue(result.isEmpty()); }
@Test public void buildCidMap__onMultipartWithNoParts__shouldReturnEmptyMap() throws Exception { Multipart multipartBody = MimeMultipart.newInstance(); Part multipartPart = new MimeBodyPart(multipartBody); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart); assertTrue(result.isEmpty()); }
@Test public void buildCidMap__onMultipartWithEmptyBodyPart__shouldReturnEmptyMap() throws Exception { Multipart multipartBody = MimeMultipart.newInstance(); BodyPart bodyPart = spy(new MimeBodyPart()); Part multipartPart = new MimeBodyPart(multipartBody); multipartBody.addBodyPart(bodyPart); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart); verify(bodyPart).getContentId(); assertTrue(result.isEmpty()); }
@Test public void buildCidMap__onTwoPart__shouldReturnBothUris() throws Exception { Multipart multipartBody = MimeMultipart.newInstance(); Part multipartPart = new MimeBodyPart(multipartBody); BodyPart subPart1 = new MimeBodyPart(); BodyPart subPart2 = new MimeBodyPart(); multipartBody.addBodyPart(subPart1); multipartBody.addBodyPart(subPart2); subPart1.setHeader(MimeHeader.HEADER_CONTENT_ID, "cid-1"); subPart2.setHeader(MimeHeader.HEADER_CONTENT_ID, "cid-2"); when(attachmentInfoExtractor.extractAttachmentInfo(subPart1)).thenReturn(new AttachmentViewInfo( null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_1, false, subPart1, true)); when(attachmentInfoExtractor.extractAttachmentInfo(subPart2)).thenReturn(new AttachmentViewInfo( null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_2, false, subPart2, true)); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart); assertEquals(2, result.size()); assertEquals(ATTACHMENT_TEST_URI_1, result.get("cid-1")); assertEquals(ATTACHMENT_TEST_URI_2, result.get("cid-2")); } |
### Question:
AutocryptHeader { String toRawHeaderString() { if (!parameters.isEmpty()) { throw new UnsupportedOperationException("arbitrary parameters not supported"); } StringBuilder builder = new StringBuilder(); builder.append(AutocryptHeader.AUTOCRYPT_HEADER).append(": "); builder.append(AutocryptHeader.AUTOCRYPT_PARAM_ADDR).append('=').append(addr).append("; "); if (isPreferEncryptMutual) { builder.append(AutocryptHeader.AUTOCRYPT_PARAM_PREFER_ENCRYPT) .append('=').append(AutocryptHeader.AUTOCRYPT_PREFER_ENCRYPT_MUTUAL).append("; "); } builder.append(AutocryptHeader.AUTOCRYPT_PARAM_KEY_DATA).append("="); appendBase64KeyData(builder); return builder.toString(); } AutocryptHeader(@NonNull Map<String, String> parameters, @NonNull String addr,
@NonNull byte[] keyData, boolean isPreferEncryptMutual); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toRawHeaderString_returnsExpected() throws Exception { AutocryptHeader autocryptHeader = new AutocryptHeader(PARAMETERS, ADDR, KEY_DATA, IS_PREFER_ENCRYPT_MUTUAL); String autocryptHeaderString = autocryptHeader.toRawHeaderString(); String expected = "Autocrypt: addr=addr; prefer-encrypt=mutual; keydata=dGhlc2VhcmUxMjBjaGFyYWN\r\n" + " 0ZXJzeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh\r\n" + " 4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4"; assertEquals(expected, autocryptHeaderString); }
@Test public void toRawHeaderString_withLongAddress_returnsExpected() throws Exception { AutocryptHeader autocryptHeader = new AutocryptHeader(PARAMETERS, ADDR_LONG, KEY_DATA, IS_PREFER_ENCRYPT_MUTUAL); String autocryptHeaderString = autocryptHeader.toRawHeaderString(); String expected = "Autocrypt: addr=veryveryverylongaddressthatspansmorethanalinelengthintheheader; prefer-encrypt=mutual; keydata=\r\n" + " dGhlc2VhcmUxMjBjaGFyYWN0ZXJzeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4\r\n" + " eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4\r\n" + " eHh4eHh4"; assertEquals(expected, autocryptHeaderString); }
@Test public void toRawHeaderString_withShortData_returnsExpected() throws Exception { AutocryptHeader autocryptHeader = new AutocryptHeader(PARAMETERS, ADDR, KEY_DATA_SHORT, IS_PREFER_ENCRYPT_MUTUAL); String autocryptHeaderString = autocryptHeader.toRawHeaderString(); String expected = "Autocrypt: addr=addr; prefer-encrypt=mutual; keydata=dGhlc2VhcmUxNWNoYXJz"; assertEquals(expected, autocryptHeaderString); } |
### Question:
AutocryptHeaderParser { @Nullable AutocryptHeader getValidAutocryptHeader(Message currentMessage) { String[] headers = currentMessage.getHeader(AutocryptHeader.AUTOCRYPT_HEADER); ArrayList<AutocryptHeader> autocryptHeaders = parseAllAutocryptHeaders(headers); boolean isSingleValidHeader = autocryptHeaders.size() == 1; return isSingleValidHeader ? autocryptHeaders.get(0) : null; } private AutocryptHeaderParser(); static AutocryptHeaderParser getInstance(); }### Answer:
@Test public void getValidAutocryptHeader__withNoHeader__shouldReturnNull() throws Exception { MimeMessage message = parseFromResource("autocrypt/no_autocrypt.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNull(autocryptHeader); }
@Test public void getValidAutocryptHeader__withBrokenBase64__shouldReturnNull() throws Exception { MimeMessage message = parseFromResource("autocrypt/rsa2048-broken-base64.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNull(autocryptHeader); }
@Test public void getValidAutocryptHeader__withSimpleAutocrypt() throws Exception { MimeMessage message = parseFromResource("autocrypt/rsa2048-simple.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNotNull(autocryptHeader); assertEquals("[email protected]", autocryptHeader.addr); assertEquals(0, autocryptHeader.parameters.size()); assertEquals(1225, autocryptHeader.keyData.length); }
@Test public void getValidAutocryptHeader__withExplicitType() throws Exception { MimeMessage message = parseFromResource("autocrypt/rsa2048-explicit-type.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNotNull(autocryptHeader); assertEquals("[email protected]", autocryptHeader.addr); assertEquals(0, autocryptHeader.parameters.size()); }
@Test public void getValidAutocryptHeader__withUnknownType__shouldReturnNull() throws Exception { MimeMessage message = parseFromResource("autocrypt/unknown-type.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNull(autocryptHeader); }
@Test public void getValidAutocryptHeader__withUnknownCriticalHeader__shouldReturnNull() throws Exception { MimeMessage message = parseFromResource("autocrypt/rsa2048-unknown-critical.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNull(autocryptHeader); }
@Test public void getValidAutocryptHeader__withUnknownNonCriticalHeader() throws Exception { MimeMessage message = parseFromResource("autocrypt/rsa2048-unknown-non-critical.eml"); AutocryptHeader autocryptHeader = autocryptHeaderParser.getValidAutocryptHeader(message); assertNotNull(autocryptHeader); assertEquals("[email protected]", autocryptHeader.addr); assertEquals(1, autocryptHeader.parameters.size()); assertEquals("ignore", autocryptHeader.parameters.get("_monkey")); } |
### Question:
EmailProviderCache { public static synchronized EmailProviderCache getCache(String accountUuid, Context context) { if (sContext == null) { sContext = context.getApplicationContext(); } EmailProviderCache instance = sInstances.get(accountUuid); if (instance == null) { instance = new EmailProviderCache(accountUuid); sInstances.put(accountUuid, instance); } return instance; } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer:
@Test public void getCache_returnsDifferentCacheForEachUUID() { EmailProviderCache cache = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); EmailProviderCache cache2 = EmailProviderCache.getCache("u002", RuntimeEnvironment.application); assertNotEquals(cache, cache2); }
@Test public void getCache_returnsSameCacheForAUUID() { EmailProviderCache cache = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); EmailProviderCache cache2 = EmailProviderCache.getCache("u001", RuntimeEnvironment.application); assertSame(cache, cache2); } |
### Question:
EmailProviderCache { public String getValueForMessage(Long messageId, String columnName) { synchronized (mMessageCache) { Map<String, String> map = mMessageCache.get(messageId); return (map == null) ? null : map.get(columnName); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer:
@Test public void getValueForUnknownMessage_returnsNull() { String result = cache.getValueForMessage(1L, "subject"); assertNull(result); } |
### Question:
EmailProviderCache { public String getValueForThread(Long threadRootId, String columnName) { synchronized (mThreadCache) { Map<String, String> map = mThreadCache.get(threadRootId); return (map == null) ? null : map.get(columnName); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer:
@Test public void getValueForUnknownThread_returnsNull() { String result = cache.getValueForThread(1L, "subject"); assertNull(result); } |
### Question:
EmailProviderCache { public boolean isMessageHidden(Long messageId, long folderId) { synchronized (mHiddenMessageCache) { Long hiddenInFolder = mHiddenMessageCache.get(messageId); return (hiddenInFolder != null && hiddenInFolder.longValue() == folderId); } } private EmailProviderCache(String accountUuid); static synchronized EmailProviderCache getCache(String accountUuid, Context context); String getValueForMessage(Long messageId, String columnName); String getValueForThread(Long threadRootId, String columnName); void setValueForMessages(List<Long> messageIds, String columnName, String value); void setValueForThreads(List<Long> threadRootIds, String columnName, String value); void removeValueForMessages(List<Long> messageIds, String columnName); void removeValueForThreads(List<Long> threadRootIds, String columnName); void hideMessages(List<LocalMessage> messages); boolean isMessageHidden(Long messageId, long folderId); void unhideMessages(List<? extends Message> messages); static final String ACTION_CACHE_UPDATED; }### Answer:
@Test public void isMessageHidden_returnsFalseForUnknownMessage() { boolean result = cache.isMessageHidden(localMessageId, localMessageFolderId); assertFalse(result); } |
### Question:
IdentityHelper { public static Identity getRecipientIdentityFromMessage(Account account, Message message) { Identity recipient = null; for (Address address : message.getRecipients(Message.RecipientType.X_ORIGINAL_TO)) { Identity identity = account.findIdentity(address); if (identity != null) { recipient = identity; break; } } if (recipient == null) { for (Address address : message.getRecipients(Message.RecipientType.DELIVERED_TO)) { Identity identity = account.findIdentity(address); if (identity != null) { recipient = identity; break; } } } if (recipient == null) { for (Address address : message.getRecipients(Message.RecipientType.X_ENVELOPE_TO)) { Identity identity = account.findIdentity(address); if (identity != null) { recipient = identity; break; } } } if (recipient == null) { for (Address address : message.getRecipients(Message.RecipientType.TO)) { Identity identity = account.findIdentity(address); if (identity != null) { recipient = identity; break; } } } if (recipient == null) { Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC); if (ccAddresses.length > 0) { for (Address address : ccAddresses) { Identity identity = account.findIdentity(address); if (identity != null) { recipient = identity; break; } } } } if (recipient == null) { recipient = account.getIdentity(0); } return recipient; } static Identity getRecipientIdentityFromMessage(Account account, Message message); }### Answer:
@Test public void testXOriginalTo() throws Exception { Address[] addresses = {new Address("[email protected]")}; msg.setRecipients(Message.RecipientType.X_ORIGINAL_TO, addresses); Identity identity = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(identity.getEmail().equalsIgnoreCase("[email protected]")); }
@Test public void testTo_withoutXOriginalTo() throws Exception { Identity eva = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(eva.getEmail().equalsIgnoreCase("[email protected]")); }
@Test public void testDeliveredTo() throws Exception { Address[] addresses = {new Address("[email protected]")}; msg.setRecipients(Message.RecipientType.DELIVERED_TO, addresses); msg.removeHeader("X-Original-To"); Identity identity = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(identity.getEmail().equalsIgnoreCase("[email protected]")); }
@Test public void testXEnvelopeTo() throws Exception { Address[] addresses = {new Address("[email protected]")}; msg.setRecipients(Message.RecipientType.X_ENVELOPE_TO, addresses); msg.removeHeader("X-Original-To"); msg.removeHeader("Delivered-To"); Identity identity = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(identity.getEmail().equalsIgnoreCase("[email protected]")); }
@Test public void testXEnvelopeTo_withXOriginalTo() throws Exception { Address[] addresses = {new Address("[email protected]")}; Address[] xoriginaltoaddresses = {new Address("[email protected]")}; msg.setRecipients(Message.RecipientType.X_ENVELOPE_TO, addresses); msg.setRecipients(Message.RecipientType.X_ORIGINAL_TO, xoriginaltoaddresses); Identity identity = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(identity.getEmail().equalsIgnoreCase("[email protected]")); } |
### Question:
K9AlarmManager { public void set(int type, long triggerAtMillis, PendingIntent operation) { if (dozeChecker.isDeviceIdleModeSupported() && dozeChecker.isAppWhitelisted()) { setAndAllowWhileIdle(type, triggerAtMillis, operation); } else { alarmManager.set(type, triggerAtMillis, operation); } } @VisibleForTesting K9AlarmManager(AlarmManager alarmManager, DozeChecker dozeChecker); static K9AlarmManager getAlarmManager(Context context); void set(int type, long triggerAtMillis, PendingIntent operation); void cancel(PendingIntent operation); }### Answer:
@Test public void set_withoutDozeSupport_shouldCallSetOnAlarmManager() throws Exception { configureDozeSupport(false); alarmManager.set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); verify(systemAlarmManager).set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); }
@Test public void set_withDozeSupportAndNotWhiteListed_shouldCallSetOnAlarmManager() throws Exception { configureDozeSupport(true); alarmManager.set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); verify(systemAlarmManager).set(TIMER_TYPE, TIMEOUT, PENDING_INTENT); } |
### Question:
K9AlarmManager { public void cancel(PendingIntent operation) { alarmManager.cancel(operation); } @VisibleForTesting K9AlarmManager(AlarmManager alarmManager, DozeChecker dozeChecker); static K9AlarmManager getAlarmManager(Context context); void set(int type, long triggerAtMillis, PendingIntent operation); void cancel(PendingIntent operation); }### Answer:
@Test public void cancel_shouldCallCancelOnAlarmManager() throws Exception { configureDozeSupport(true); addAppToBatteryOptimizationWhitelist(); alarmManager.cancel(PENDING_INTENT); verify(systemAlarmManager).cancel(PENDING_INTENT); } |
### Question:
Utility { public static String stripNewLines(String multiLineString) { return multiLineString.replaceAll("[\\r\\n]", ""); } static boolean arrayContains(Object[] a, Object o); static boolean isAnyMimeType(String o, String... a); static boolean arrayContainsAny(Object[] a, Object... o); static String combine(Object[] parts, char separator); static String combine(Iterable<?> parts, char separator); static boolean requiredFieldValid(TextView view); static boolean requiredFieldValid(Editable s); static boolean domainFieldValid(EditText view); static void setCompoundDrawablesAlpha(TextView view, int alpha); static String wrap(String str, int wrapLength); static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords); static String stripSubject(final String subject); static String stripNewLines(String multiLineString); static boolean hasExternalImages(final String message); static void closeQuietly(final Cursor cursor); static boolean hasConnectivity(final Context context); static List<String> extractMessageIds(final String text); static String extractMessageId(final String text); static Handler getMainThreadHandler(); static void setContactForBadge(ContactBadge contactBadge,
Address address); }### Answer:
@Test public void stripNewLines_removesLeadingCarriageReturns() { String result = Utility.stripNewLines("\r\rTest"); assertEquals("Test", result); }
@Test public void stripNewLines_removesLeadingLineFeeds() { String result = Utility.stripNewLines("\n\nTest\n\n"); assertEquals("Test", result); }
@Test public void stripNewLines_removesTrailingCarriageReturns() { String result = Utility.stripNewLines("Test\r\r"); assertEquals("Test", result); }
@Test public void stripNewLines_removesMidCarriageReturns() { String result = Utility.stripNewLines("Test\rTest"); assertEquals("TestTest", result); }
@Test public void stripNewLines_removesMidLineFeeds() { String result = Utility.stripNewLines("Test\nTest"); assertEquals("TestTest", result); } |
### Question:
MailTo { public static boolean isMailTo(Uri uri) { return uri != null && MAILTO_SCHEME.equals(uri.getScheme()); } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void testIsMailTo_nullArgument() { Uri uri = null; boolean result = MailTo.isMailTo(uri); assertFalse(result); } |
### Question:
MailTo { public static MailTo parse(Uri uri) throws NullPointerException, IllegalArgumentException { if (uri == null || uri.toString() == null) { throw new NullPointerException("Argument 'uri' must not be null"); } if (!isMailTo(uri)) { throw new IllegalArgumentException("Not a mailto scheme"); } String schemaSpecific = uri.getSchemeSpecificPart(); int end = schemaSpecific.indexOf('?'); if (end == -1) { end = schemaSpecific.length(); } CaseInsensitiveParamWrapper params = new CaseInsensitiveParamWrapper(Uri.parse("foo: String recipient = Uri.decode(schemaSpecific.substring(0, end)); List<String> toList = params.getQueryParameters(TO); if (recipient.length() != 0) { toList.add(0, recipient); } List<String> ccList = params.getQueryParameters(CC); List<String> bccList = params.getQueryParameters(BCC); Address[] toAddresses = toAddressArray(toList); Address[] ccAddresses = toAddressArray(ccList); Address[] bccAddresses = toAddressArray(bccList); String subject = getFirstParameterValue(params, SUBJECT); String body = getFirstParameterValue(params, BODY); return new MailTo(toAddresses, ccAddresses, bccAddresses, subject, body); } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer:
@Test public void parse_withNullArgument_shouldThrow() throws Exception { exception.expect(NullPointerException.class); exception.expectMessage("Argument 'uri' must not be null"); MailTo.parse(null); }
@Test public void parse_withoutMailtoUri_shouldThrow() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("Not a mailto scheme"); Uri uri = Uri.parse("http: MailTo.parse(uri); }
@Test public void testCaseInsensitiveParamWrapper() { Uri uri = Uri.parse("scheme: CaseInsensitiveParamWrapper caseInsensitiveParamWrapper = new CaseInsensitiveParamWrapper(uri); List<String> result = caseInsensitiveParamWrapper.getQueryParameters("b"); assertThat(Collections.singletonList("two"), is(result)); }
@Test public void testCaseInsensitiveParamWrapper_multipleMatchingQueryParameters() { Uri uri = Uri.parse("scheme: CaseInsensitiveParamWrapper caseInsensitiveParamWrapper = new CaseInsensitiveParamWrapper(uri); List<String> result = caseInsensitiveParamWrapper.getQueryParameters("name"); assertThat(Arrays.asList("two", "Three", "FOUR"), is(result)); }
@Test public void testCaseInsensitiveParamWrapper_withoutQueryParameters() { Uri uri = Uri.parse("scheme: CaseInsensitiveParamWrapper caseInsensitiveParamWrapper = new CaseInsensitiveParamWrapper(uri); List<String> result = caseInsensitiveParamWrapper.getQueryParameters("name"); assertThat(Collections.<String>emptyList(), is(result)); } |
### Question:
MailTo { public String getSubject() { return subject; } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer:
@Test public void testGetSubject() { Uri uri = Uri.parse("mailto:?subject=Hello"); MailTo mailToHelper = MailTo.parse(uri); String subject = mailToHelper.getSubject(); assertEquals(subject, "Hello"); } |
### Question:
MailTo { public String getBody() { return body; } private MailTo(Address[] toAddresses, Address[] ccAddresses, Address[] bccAddresses, String subject, String body); static boolean isMailTo(Uri uri); static MailTo parse(Uri uri); Address[] getTo(); Address[] getCc(); Address[] getBcc(); String getSubject(); String getBody(); }### Answer:
@Test public void testGetBody() { Uri uri = Uri.parse("mailto:?body=Test%20Body&something=else"); MailTo mailToHelper = MailTo.parse(uri); String subject = mailToHelper.getBody(); assertEquals(subject, "Test Body"); } |
### Question:
EmailHelper { public static String getDomainFromEmailAddress(String email) { int separatorIndex = email.lastIndexOf('@'); if (separatorIndex == -1 || separatorIndex + 1 == email.length()) { return null; } return email.substring(separatorIndex + 1); } private EmailHelper(); static String getDomainFromEmailAddress(String email); }### Answer:
@Test public void getDomainFromEmailAddress_withRegularEmail_shouldReturnsDomain() { String result = EmailHelper.getDomainFromEmailAddress("[email protected]"); assertEquals("domain.com", result); }
@Test public void getDomainFromEmailAddress_withInvalidEmail_shouldReturnNull() { String result = EmailHelper.getDomainFromEmailAddress("user"); assertNull(result); }
@Test public void getDomainFromEmailAddress_withTLD_shouldReturnDomain() { String result = EmailHelper.getDomainFromEmailAddress("user@domain"); assertEquals("domain", result); } |
### Question:
MessageHelper { public static CharSequence toFriendly(Address address, Contacts contacts) { return toFriendly(address,contacts, QMail.showCorrespondentNames(), QMail.changeContactNameColor(), QMail.getContactNameColor()); } private MessageHelper(final Context context); synchronized static MessageHelper getInstance(final Context context); void populate(final MessageInfoHolder target,
final LocalMessage message,
final FolderInfoHolder folder,
Account account,
boolean canUseContacts); CharSequence getDisplayName(Account account, Address[] fromAddrs, Address[] toAddrs, boolean canUseContacts); boolean toMe(Account account, Address[] toAddrs); static CharSequence toFriendly(Address address, Contacts contacts); static CharSequence toFriendly(Address[] addresses, Contacts contacts); }### Answer:
@Test public void testToFriendlyShowsPersonalPartIfItExists() throws Exception { Address address = new Address("[email protected]", "Tim Testor"); assertEquals("Tim Testor", MessageHelper.toFriendly(address, contacts)); }
@Test public void testToFriendlyShowsEmailPartIfNoPersonalPartExists() throws Exception { Address address = new Address("[email protected]"); assertEquals("[email protected]", MessageHelper.toFriendly(address, contacts)); }
@Test public void testToFriendlyArray() throws Exception { Address address1 = new Address("[email protected]", "Tim Testor"); Address address2 = new Address("[email protected]", "Foo Bar"); Address[] addresses = new Address[] { address1, address2 }; assertEquals("Tim Testor,Foo Bar", MessageHelper.toFriendly(addresses, contacts).toString()); }
@Test public void testToFriendlyWithContactLookup() throws Exception { Address address = new Address("[email protected]"); assertEquals("Tim Testor", MessageHelper.toFriendly(address, mockContacts).toString()); }
@Test public void testToFriendlyWithChangeContactColor() throws Exception { Address address = new Address("[email protected]"); CharSequence friendly = MessageHelper.toFriendly(address, mockContacts, true, true, Color.RED); assertTrue(friendly instanceof SpannableString); assertEquals("Tim Testor", friendly.toString()); }
@Test public void testToFriendlyWithoutCorrespondentNames() throws Exception { Address address = new Address("[email protected]", "Tim Testor"); CharSequence friendly = MessageHelper.toFriendly(address, mockContacts, false, false, 0); assertEquals("[email protected]", friendly.toString()); } |
### Question:
ReplyToParser { public ReplyToAddresses getRecipientsToReplyTo(Message message, Account account) { Address[] candidateAddress; Address[] replyToAddresses = message.getReplyTo(); Address[] fromAddresses = message.getFrom(); if (replyToAddresses.length > 0) { candidateAddress = replyToAddresses; } else { candidateAddress = fromAddresses; } boolean replyToAddressIsUserIdentity = account.isAnIdentity(candidateAddress); if (replyToAddressIsUserIdentity) { candidateAddress = message.getRecipients(RecipientType.TO); } return new ReplyToAddresses(candidateAddress); } ReplyToAddresses getRecipientsToReplyTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyAllTo(Message message, Account account); }### Answer:
@Test public void getRecipientsToReplyTo_should_prefer_replyTo_over_any_other_field() throws Exception { when(message.getReplyTo()).thenReturn(REPLY_TO_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(LIST_POST_HEADER_VALUES); when(message.getFrom()).thenReturn(FROM_ADDRESSES); ReplyToAddresses result = replyToParser.getRecipientsToReplyTo(message, account); assertArrayEquals(REPLY_TO_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); verify(account).isAnIdentity(result.to); }
@Test public void getRecipientsToReplyTo_should_prefer_from_ifOtherIsIdentity() throws Exception { when(message.getReplyTo()).thenReturn(REPLY_TO_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(LIST_POST_HEADER_VALUES); when(message.getFrom()).thenReturn(FROM_ADDRESSES); when(message.getRecipients(RecipientType.TO)).thenReturn(TO_ADDRESSES); when(account.isAnIdentity(any(Address[].class))).thenReturn(true); ReplyToAddresses result = replyToParser.getRecipientsToReplyTo(message, account); assertArrayEquals(TO_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); }
@Test public void getRecipientsToReplyTo_should_return_from_otherwise() throws Exception { when(message.getReplyTo()).thenReturn(EMPTY_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(new String[0]); when(message.getFrom()).thenReturn(FROM_ADDRESSES); ReplyToAddresses result = replyToParser.getRecipientsToReplyTo(message, account); assertArrayEquals(FROM_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); verify(account).isAnIdentity(result.to); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.