src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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; } | @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); } |
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; } | @Test public void testPercentEncode() throws Exception { String decoded = "some!@#%weird\"value1"; String encoded = OAuthUtils.percentEncode(decoded); assertEquals("some%21%40%23%25weird%22value1", encoded); } |
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; } | @Test public void testInstantiateClass() throws Exception { StringBuilder builder = OAuthUtils.instantiateClass(StringBuilder.class); assertNotNull(builder); } |
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; } | @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()); } |
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; } | @Test public void testGetAuthHeaderField() throws Exception { String token = OAuthUtils.getAuthHeaderField("Bearer 312ewqdsad"); assertEquals("312ewqdsad", token); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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); } |
SignatureMethodRSAImpl implements SignatureMethod<PrivateKey, PublicKey> { @Override public boolean verify(String signature, String header, String payload, PublicKey verifyingKey) { byte[] token = toToken(header, payload); try { Signature sign = Signature.getInstance(getAlgorithmInternal()); sign.initVerify(verifyingKey.getPublicKey()); sign.update(token); return sign.verify(decode(signature)); } catch (Exception e) { return false; } } SignatureMethodRSAImpl(String algorithm); @Override String calculate(String header, String payload, PrivateKey signingKey); @Override boolean verify(String signature, String header, String payload, PublicKey verifyingKey); @Override String getAlgorithm(); } | @Test public void testVerify() throws Exception{ final byte[] n = { (byte) 161, (byte) 248, (byte) 22, (byte) 10, (byte) 226, (byte) 227, (byte) 201, (byte) 180, (byte) 101, (byte) 206, (byte) 141, (byte) 45, (byte) 101, (byte) 98, (byte) 99, (byte) 54, (byte) 43, (byte) 146, (byte) 125, (byte) 190, (byte) 41, (byte) 225, (byte) 240, (byte) 36, (byte) 119, (byte) 252, (byte) 22, (byte) 37, (byte) 204, (byte) 144, (byte) 161, (byte) 54, (byte) 227, (byte) 139, (byte) 217, (byte) 52, (byte) 151, (byte) 197, (byte) 182, (byte) 234, (byte) 99, (byte) 221, (byte) 119, (byte) 17, (byte) 230, (byte) 124, (byte) 116, (byte) 41, (byte) 249, (byte) 86, (byte) 176, (byte) 251, (byte) 138, (byte) 143, (byte) 8, (byte) 154, (byte) 220, (byte) 75, (byte) 105, (byte) 137, (byte) 60, (byte) 193, (byte) 51, (byte) 63, (byte) 83, (byte) 237, (byte) 208, (byte) 25, (byte) 184, (byte) 119, (byte) 132, (byte) 37, (byte) 47, (byte) 236, (byte) 145, (byte) 79, (byte) 228, (byte) 133, (byte) 119, (byte) 105, (byte) 89, (byte) 75, (byte) 234, (byte) 66, (byte) 128, (byte) 211, (byte) 44, (byte) 15, (byte) 85, (byte) 191, (byte) 98, (byte) 148, (byte) 79, (byte) 19, (byte) 3, (byte) 150, (byte) 188, (byte) 110, (byte) 155, (byte) 223, (byte) 110, (byte) 189, (byte) 210, (byte) 189, (byte) 163, (byte) 103, (byte) 142, (byte) 236, (byte) 160, (byte) 198, (byte) 104, (byte) 247, (byte) 1, (byte) 179, (byte) 141, (byte) 191, (byte) 251, (byte) 56, (byte) 200, (byte) 52, (byte) 44, (byte) 226, (byte) 254, (byte) 109, (byte) 39, (byte) 250, (byte) 222, (byte) 74, (byte) 90, (byte) 72, (byte) 116, (byte) 151, (byte) 157, (byte) 212, (byte) 185, (byte) 207, (byte) 154, (byte) 222, (byte) 196, (byte) 199, (byte) 91, (byte) 5, (byte) 133, (byte) 44, (byte) 44, (byte) 15, (byte) 94, (byte) 248, (byte) 165, (byte) 193, (byte) 117, (byte) 3, (byte) 146, (byte) 249, (byte) 68, (byte) 232, (byte) 237, (byte) 100, (byte) 193, (byte) 16, (byte) 198, (byte) 182, (byte) 71, (byte) 96, (byte) 154, (byte) 164, (byte) 120, (byte) 58, (byte) 235, (byte) 156, (byte) 108, (byte) 154, (byte) 215, (byte) 85, (byte) 49, (byte) 48, (byte) 80, (byte) 99, (byte) 139, (byte) 131, (byte) 102, (byte) 92, (byte) 111, (byte) 111, (byte) 122, (byte) 130, (byte) 163, (byte) 150, (byte) 112, (byte) 42, (byte) 31, (byte) 100, (byte) 27, (byte) 130, (byte) 211, (byte) 235, (byte) 242, (byte) 57, (byte) 34, (byte) 25, (byte) 73, (byte) 31, (byte) 182, (byte) 134, (byte) 135, (byte) 44, (byte) 87, (byte) 22, (byte) 245, (byte) 10, (byte) 248, (byte) 53, (byte) 141, (byte) 154, (byte) 139, (byte) 157, (byte) 23, (byte) 195, (byte) 64, (byte) 114, (byte) 143, (byte) 127, (byte) 135, (byte) 216, (byte) 154, (byte) 24, (byte) 216, (byte) 252, (byte) 171, (byte) 103, (byte) 173, (byte) 132, (byte) 89, (byte) 12, (byte) 46, (byte) 207, (byte) 117, (byte) 147, (byte) 57, (byte) 54, (byte) 60, (byte) 7, (byte) 3, (byte) 77, (byte) 111, (byte) 96, (byte) 111, (byte) 158, (byte) 33, (byte) 224, (byte) 84, (byte) 86, (byte) 202, (byte) 229, (byte) 233, (byte) 161 }; final byte[] e = { 1, 0, 1 }; final byte[] d = { 18, (byte) 174, (byte) 113, (byte) 164, (byte) 105, (byte) 205, (byte) 10, (byte) 43, (byte) 195, (byte) 126, (byte) 82, (byte) 108, (byte) 69, (byte) 0, (byte) 87, (byte) 31, (byte) 29, (byte) 97, (byte) 117, (byte) 29, (byte) 100, (byte) 233, (byte) 73, (byte) 112, (byte) 123, (byte) 98, (byte) 89, (byte) 15, (byte) 157, (byte) 11, (byte) 165, (byte) 124, (byte) 150, (byte) 60, (byte) 64, (byte) 30, (byte) 63, (byte) 207, (byte) 47, (byte) 44, (byte) 211, (byte) 189, (byte) 236, (byte) 136, (byte) 229, (byte) 3, (byte) 191, (byte) 198, (byte) 67, (byte) 155, (byte) 11, (byte) 40, (byte) 200, (byte) 47, (byte) 125, (byte) 55, (byte) 151, (byte) 103, (byte) 31, (byte) 82, (byte) 19, (byte) 238, (byte) 216, (byte) 193, (byte) 90, (byte) 37, (byte) 216, (byte) 213, (byte) 206, (byte) 160, (byte) 2, (byte) 94, (byte) 227, (byte) 171, (byte) 46, (byte) 139, (byte) 127, (byte) 121, (byte) 33, (byte) 111, (byte) 198, (byte) 59, (byte) 234, (byte) 86, (byte) 39, (byte) 83, (byte) 180, (byte) 6, (byte) 68, (byte) 198, (byte) 161, (byte) 81, (byte) 39, (byte) 217, (byte) 178, (byte) 149, (byte) 69, (byte) 64, (byte) 160, (byte) 187, (byte) 225, (byte) 163, (byte) 5, (byte) 86, (byte) 152, (byte) 45, (byte) 78, (byte) 159, (byte) 222, (byte) 95, (byte) 100, (byte) 37, (byte) 241, (byte) 77, (byte) 75, (byte) 113, (byte) 52, (byte) 65, (byte) 181, (byte) 93, (byte) 199, (byte) 59, (byte) 155, (byte) 74, (byte) 237, (byte) 204, (byte) 146, (byte) 172, (byte) 227, (byte) 146, (byte) 126, (byte) 55, (byte) 245, (byte) 125, (byte) 12, (byte) 253, (byte) 94, (byte) 117, (byte) 129, (byte) 250, (byte) 81, (byte) 44, (byte) 143, (byte) 73, (byte) 97, (byte) 169, (byte) 235, (byte) 11, (byte) 128, (byte) 248, (byte) 168, (byte) 7, (byte) 70, (byte) 114, (byte) 138, (byte) 85, (byte) 255, (byte) 70, (byte) 71, (byte) 31, (byte) 52, (byte) 37, (byte) 6, (byte) 59, (byte) 157, (byte) 83, (byte) 100, (byte) 47, (byte) 94, (byte) 222, (byte) 30, (byte) 132, (byte) 214, (byte) 19, (byte) 8, (byte) 26, (byte) 250, (byte) 92, (byte) 34, (byte) 208, (byte) 81, (byte) 40, (byte) 91, (byte) 214, (byte) 59, (byte) 148, (byte) 59, (byte) 86, (byte) 93, (byte) 137, (byte) 138, (byte) 5, (byte) 104, (byte) 84, (byte) 19, (byte) 229, (byte) 60, (byte) 60, (byte) 108, (byte) 101, (byte) 37, (byte) 255, (byte) 31, (byte) 227, (byte) 78, (byte) 61, (byte) 220, (byte) 112, (byte) 240, (byte) 213, (byte) 100, (byte) 80, (byte) 253, (byte) 164, (byte) 139, (byte) 161, (byte) 46, (byte) 16, (byte) 78, (byte) 157, (byte) 235, (byte) 159, (byte) 184, (byte) 24, (byte) 129, (byte) 225, (byte) 196, (byte) 189, (byte) 242, (byte) 93, (byte) 146, (byte) 71, (byte) 244, (byte) 80, (byte) 200, (byte) 101, (byte) 146, (byte) 121, (byte) 104, (byte) 231, (byte) 115, (byte) 52, (byte) 244, (byte) 65, (byte) 79, (byte) 117, (byte) 167, (byte) 80, (byte) 225, (byte) 57, (byte) 84, (byte) 110, (byte) 58, (byte) 138, (byte) 115, (byte) 157 }; BigInteger N = new BigInteger(1, n); BigInteger E = new BigInteger(1, e); BigInteger D = new BigInteger(1, d); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(N, E); RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(N, D); rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); rsaPrivKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec); String accessToken = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"; String jwt[] = accessToken.split("\\."); assertTrue(sRsaImpl.verify(jwt[2], jwt[0], jwt[1], new PublicKey(rsaPublicKey))); }
@Test public void testVerifyCookbook() throws Exception{ final byte[] n = TokenDecoder.base64DecodeToByte("n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw"); final byte[] e =TokenDecoder.base64DecodeToByte("AQAB"); final byte[] d = TokenDecoder.base64DecodeToByte("bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ"); BigInteger N = new BigInteger(1, n); BigInteger E = new BigInteger(1, e); BigInteger D = new BigInteger(1, d); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(N, E); RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(N, D); rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); rsaPrivKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec); String accessToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9." + "SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IH" + "lvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBk" + "b24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcm" + "UgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4." + "MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmK" + "ZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4J" + "IwmDLJK3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8w" + "W1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluP" + "xUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_f" + "cIe8u9ipH84ogoree7vjbU5y18kDquDg"; String jwt[] = accessToken.split("\\."); assertTrue(sRsaImpl.verify(jwt[2], jwt[0], jwt[1], new PublicKey(rsaPublicKey))); } |
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; } | @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); } |
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; } | @Test public void testGetAuthzMethod() throws Exception { String authzMethod = OAuthUtils.getAuthzMethod("Basic dXNlcjpwYXNzd29yZA=="); assertEquals("Basic", authzMethod); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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)); } |
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); } | @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)); } |
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); } | @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")); } |
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); } | @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); } |
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); } | @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")); } |
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); } | @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")); } |
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(); } | @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); } |
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(); } | @Test public void allowStringResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(STRING_BYTES); assertEquals("getBody() should return correct string", STRING, resp.getBody()); } |
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); } | @Test public void testCreateGitHubTokenResponse() throws Exception { OAuthClientResponse gitHubTokenResponse = OAuthClientResponseFactory .createGitHubTokenResponse("access_token=123", OAuth.ContentType.URL_ENCODED, 200); assertNotNull(gitHubTokenResponse); } |
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); } | @Test public void testCreateJSONTokenResponse() throws Exception { OAuthClientResponse jsonTokenResponse = OAuthClientResponseFactory .createJSONTokenResponse("{\"access_token\":\"123\"}", OAuth.ContentType.JSON, 200); assertNotNull(jsonTokenResponse); } |
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); } | @Test public void testCreateCustomResponse() throws Exception { } |
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(); } | @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()); } } |
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(); } | @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()); } } |
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(); } | @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); } |
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(); } | @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); } |
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(); } | @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); } |
JWS { public <SK extends SigningKey, VK extends VerifyingKey> boolean validate(SignatureMethod<SK, VK> method, VK verifyingKey) { if (!acceptAlgorithm(method)) { throw new IllegalArgumentException("Impossible to verify current JWS signature with algorithm '" + method.getAlgorithm() + "', JWS header specifies message has been signed with '" + header.getAlgorithm() + "' algorithm."); } if (verifyingKey == null) { throw new IllegalArgumentException("A verifying key is required in order to verify the signature."); } if (payload == null) { throw new IllegalStateException("JWS token must have a payload."); } if (signature == null) { throw new IllegalStateException("JWS token must have a signature to be verified."); } if (rawString == null) { return method.verify(signature, TokenDecoder.base64Encode(new JWSHeaderWriter().write(header)), TokenDecoder.base64Encode(payload), verifyingKey); } else { String jwt[] = rawString.split("\\."); return method.verify(jwt[2], jwt[0], jwt[1], verifyingKey); } } JWS(Header header, String payload, String signature); JWS(String rawString, Header header, String payload, String signature); Header getHeader(); String getPayload(); String getSignature(); boolean acceptAlgorithm(SignatureMethod<SK, VK> method); boolean validate(SignatureMethod<SK, VK> method,
VK verifyingKey); } | @Test public void testValidate() throws InvalidKeySpecException, NoSuchAlgorithmException { final byte[] n = { (byte) 161, (byte) 248, (byte) 22, (byte) 10, (byte) 226, (byte) 227, (byte) 201, (byte) 180, (byte) 101, (byte) 206, (byte) 141, (byte) 45, (byte) 101, (byte) 98, (byte) 99, (byte) 54, (byte) 43, (byte) 146, (byte) 125, (byte) 190, (byte) 41, (byte) 225, (byte) 240, (byte) 36, (byte) 119, (byte) 252, (byte) 22, (byte) 37, (byte) 204, (byte) 144, (byte) 161, (byte) 54, (byte) 227, (byte) 139, (byte) 217, (byte) 52, (byte) 151, (byte) 197, (byte) 182, (byte) 234, (byte) 99, (byte) 221, (byte) 119, (byte) 17, (byte) 230, (byte) 124, (byte) 116, (byte) 41, (byte) 249, (byte) 86, (byte) 176, (byte) 251, (byte) 138, (byte) 143, (byte) 8, (byte) 154, (byte) 220, (byte) 75, (byte) 105, (byte) 137, (byte) 60, (byte) 193, (byte) 51, (byte) 63, (byte) 83, (byte) 237, (byte) 208, (byte) 25, (byte) 184, (byte) 119, (byte) 132, (byte) 37, (byte) 47, (byte) 236, (byte) 145, (byte) 79, (byte) 228, (byte) 133, (byte) 119, (byte) 105, (byte) 89, (byte) 75, (byte) 234, (byte) 66, (byte) 128, (byte) 211, (byte) 44, (byte) 15, (byte) 85, (byte) 191, (byte) 98, (byte) 148, (byte) 79, (byte) 19, (byte) 3, (byte) 150, (byte) 188, (byte) 110, (byte) 155, (byte) 223, (byte) 110, (byte) 189, (byte) 210, (byte) 189, (byte) 163, (byte) 103, (byte) 142, (byte) 236, (byte) 160, (byte) 198, (byte) 104, (byte) 247, (byte) 1, (byte) 179, (byte) 141, (byte) 191, (byte) 251, (byte) 56, (byte) 200, (byte) 52, (byte) 44, (byte) 226, (byte) 254, (byte) 109, (byte) 39, (byte) 250, (byte) 222, (byte) 74, (byte) 90, (byte) 72, (byte) 116, (byte) 151, (byte) 157, (byte) 212, (byte) 185, (byte) 207, (byte) 154, (byte) 222, (byte) 196, (byte) 199, (byte) 91, (byte) 5, (byte) 133, (byte) 44, (byte) 44, (byte) 15, (byte) 94, (byte) 248, (byte) 165, (byte) 193, (byte) 117, (byte) 3, (byte) 146, (byte) 249, (byte) 68, (byte) 232, (byte) 237, (byte) 100, (byte) 193, (byte) 16, (byte) 198, (byte) 182, (byte) 71, (byte) 96, (byte) 154, (byte) 164, (byte) 120, (byte) 58, (byte) 235, (byte) 156, (byte) 108, (byte) 154, (byte) 215, (byte) 85, (byte) 49, (byte) 48, (byte) 80, (byte) 99, (byte) 139, (byte) 131, (byte) 102, (byte) 92, (byte) 111, (byte) 111, (byte) 122, (byte) 130, (byte) 163, (byte) 150, (byte) 112, (byte) 42, (byte) 31, (byte) 100, (byte) 27, (byte) 130, (byte) 211, (byte) 235, (byte) 242, (byte) 57, (byte) 34, (byte) 25, (byte) 73, (byte) 31, (byte) 182, (byte) 134, (byte) 135, (byte) 44, (byte) 87, (byte) 22, (byte) 245, (byte) 10, (byte) 248, (byte) 53, (byte) 141, (byte) 154, (byte) 139, (byte) 157, (byte) 23, (byte) 195, (byte) 64, (byte) 114, (byte) 143, (byte) 127, (byte) 135, (byte) 216, (byte) 154, (byte) 24, (byte) 216, (byte) 252, (byte) 171, (byte) 103, (byte) 173, (byte) 132, (byte) 89, (byte) 12, (byte) 46, (byte) 207, (byte) 117, (byte) 147, (byte) 57, (byte) 54, (byte) 60, (byte) 7, (byte) 3, (byte) 77, (byte) 111, (byte) 96, (byte) 111, (byte) 158, (byte) 33, (byte) 224, (byte) 84, (byte) 86, (byte) 202, (byte) 229, (byte) 233, (byte) 161 }; final byte[] e = { 1, 0, 1 }; final byte[] d = { 18, (byte) 174, (byte) 113, (byte) 164, (byte) 105, (byte) 205, (byte) 10, (byte) 43, (byte) 195, (byte) 126, (byte) 82, (byte) 108, (byte) 69, (byte) 0, (byte) 87, (byte) 31, (byte) 29, (byte) 97, (byte) 117, (byte) 29, (byte) 100, (byte) 233, (byte) 73, (byte) 112, (byte) 123, (byte) 98, (byte) 89, (byte) 15, (byte) 157, (byte) 11, (byte) 165, (byte) 124, (byte) 150, (byte) 60, (byte) 64, (byte) 30, (byte) 63, (byte) 207, (byte) 47, (byte) 44, (byte) 211, (byte) 189, (byte) 236, (byte) 136, (byte) 229, (byte) 3, (byte) 191, (byte) 198, (byte) 67, (byte) 155, (byte) 11, (byte) 40, (byte) 200, (byte) 47, (byte) 125, (byte) 55, (byte) 151, (byte) 103, (byte) 31, (byte) 82, (byte) 19, (byte) 238, (byte) 216, (byte) 193, (byte) 90, (byte) 37, (byte) 216, (byte) 213, (byte) 206, (byte) 160, (byte) 2, (byte) 94, (byte) 227, (byte) 171, (byte) 46, (byte) 139, (byte) 127, (byte) 121, (byte) 33, (byte) 111, (byte) 198, (byte) 59, (byte) 234, (byte) 86, (byte) 39, (byte) 83, (byte) 180, (byte) 6, (byte) 68, (byte) 198, (byte) 161, (byte) 81, (byte) 39, (byte) 217, (byte) 178, (byte) 149, (byte) 69, (byte) 64, (byte) 160, (byte) 187, (byte) 225, (byte) 163, (byte) 5, (byte) 86, (byte) 152, (byte) 45, (byte) 78, (byte) 159, (byte) 222, (byte) 95, (byte) 100, (byte) 37, (byte) 241, (byte) 77, (byte) 75, (byte) 113, (byte) 52, (byte) 65, (byte) 181, (byte) 93, (byte) 199, (byte) 59, (byte) 155, (byte) 74, (byte) 237, (byte) 204, (byte) 146, (byte) 172, (byte) 227, (byte) 146, (byte) 126, (byte) 55, (byte) 245, (byte) 125, (byte) 12, (byte) 253, (byte) 94, (byte) 117, (byte) 129, (byte) 250, (byte) 81, (byte) 44, (byte) 143, (byte) 73, (byte) 97, (byte) 169, (byte) 235, (byte) 11, (byte) 128, (byte) 248, (byte) 168, (byte) 7, (byte) 70, (byte) 114, (byte) 138, (byte) 85, (byte) 255, (byte) 70, (byte) 71, (byte) 31, (byte) 52, (byte) 37, (byte) 6, (byte) 59, (byte) 157, (byte) 83, (byte) 100, (byte) 47, (byte) 94, (byte) 222, (byte) 30, (byte) 132, (byte) 214, (byte) 19, (byte) 8, (byte) 26, (byte) 250, (byte) 92, (byte) 34, (byte) 208, (byte) 81, (byte) 40, (byte) 91, (byte) 214, (byte) 59, (byte) 148, (byte) 59, (byte) 86, (byte) 93, (byte) 137, (byte) 138, (byte) 5, (byte) 104, (byte) 84, (byte) 19, (byte) 229, (byte) 60, (byte) 60, (byte) 108, (byte) 101, (byte) 37, (byte) 255, (byte) 31, (byte) 227, (byte) 78, (byte) 61, (byte) 220, (byte) 112, (byte) 240, (byte) 213, (byte) 100, (byte) 80, (byte) 253, (byte) 164, (byte) 139, (byte) 161, (byte) 46, (byte) 16, (byte) 78, (byte) 157, (byte) 235, (byte) 159, (byte) 184, (byte) 24, (byte) 129, (byte) 225, (byte) 196, (byte) 189, (byte) 242, (byte) 93, (byte) 146, (byte) 71, (byte) 244, (byte) 80, (byte) 200, (byte) 101, (byte) 146, (byte) 121, (byte) 104, (byte) 231, (byte) 115, (byte) 52, (byte) 244, (byte) 65, (byte) 79, (byte) 117, (byte) 167, (byte) 80, (byte) 225, (byte) 57, (byte) 84, (byte) 110, (byte) 58, (byte) 138, (byte) 115, (byte) 157 }; BigInteger N = new BigInteger(1, n); BigInteger E = new BigInteger(1, e); BigInteger D = new BigInteger(1, d); String accessToken = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"; JWS jws = new JWSReader().read(accessToken); SignatureMethod signatureMethod = new SignatureMethodRSAImpl("RS256"); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(N, E); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); Assert.assertTrue(jws.validate(signatureMethod, new PublicKey(rsaPublicKey))); }
@Test public void testValidate2() throws InvalidKeySpecException, NoSuchAlgorithmException { final byte[] n = { (byte) 161, (byte) 248, (byte) 22, (byte) 10, (byte) 226, (byte) 227, (byte) 201, (byte) 180, (byte) 101, (byte) 206, (byte) 141, (byte) 45, (byte) 101, (byte) 98, (byte) 99, (byte) 54, (byte) 43, (byte) 146, (byte) 125, (byte) 190, (byte) 41, (byte) 225, (byte) 240, (byte) 36, (byte) 119, (byte) 252, (byte) 22, (byte) 37, (byte) 204, (byte) 144, (byte) 161, (byte) 54, (byte) 227, (byte) 139, (byte) 217, (byte) 52, (byte) 151, (byte) 197, (byte) 182, (byte) 234, (byte) 99, (byte) 221, (byte) 119, (byte) 17, (byte) 230, (byte) 124, (byte) 116, (byte) 41, (byte) 249, (byte) 86, (byte) 176, (byte) 251, (byte) 138, (byte) 143, (byte) 8, (byte) 154, (byte) 220, (byte) 75, (byte) 105, (byte) 137, (byte) 60, (byte) 193, (byte) 51, (byte) 63, (byte) 83, (byte) 237, (byte) 208, (byte) 25, (byte) 184, (byte) 119, (byte) 132, (byte) 37, (byte) 47, (byte) 236, (byte) 145, (byte) 79, (byte) 228, (byte) 133, (byte) 119, (byte) 105, (byte) 89, (byte) 75, (byte) 234, (byte) 66, (byte) 128, (byte) 211, (byte) 44, (byte) 15, (byte) 85, (byte) 191, (byte) 98, (byte) 148, (byte) 79, (byte) 19, (byte) 3, (byte) 150, (byte) 188, (byte) 110, (byte) 155, (byte) 223, (byte) 110, (byte) 189, (byte) 210, (byte) 189, (byte) 163, (byte) 103, (byte) 142, (byte) 236, (byte) 160, (byte) 198, (byte) 104, (byte) 247, (byte) 1, (byte) 179, (byte) 141, (byte) 191, (byte) 251, (byte) 56, (byte) 200, (byte) 52, (byte) 44, (byte) 226, (byte) 254, (byte) 109, (byte) 39, (byte) 250, (byte) 222, (byte) 74, (byte) 90, (byte) 72, (byte) 116, (byte) 151, (byte) 157, (byte) 212, (byte) 185, (byte) 207, (byte) 154, (byte) 222, (byte) 196, (byte) 199, (byte) 91, (byte) 5, (byte) 133, (byte) 44, (byte) 44, (byte) 15, (byte) 94, (byte) 248, (byte) 165, (byte) 193, (byte) 117, (byte) 3, (byte) 146, (byte) 249, (byte) 68, (byte) 232, (byte) 237, (byte) 100, (byte) 193, (byte) 16, (byte) 198, (byte) 182, (byte) 71, (byte) 96, (byte) 154, (byte) 164, (byte) 120, (byte) 58, (byte) 235, (byte) 156, (byte) 108, (byte) 154, (byte) 215, (byte) 85, (byte) 49, (byte) 48, (byte) 80, (byte) 99, (byte) 139, (byte) 131, (byte) 102, (byte) 92, (byte) 111, (byte) 111, (byte) 122, (byte) 130, (byte) 163, (byte) 150, (byte) 112, (byte) 42, (byte) 31, (byte) 100, (byte) 27, (byte) 130, (byte) 211, (byte) 235, (byte) 242, (byte) 57, (byte) 34, (byte) 25, (byte) 73, (byte) 31, (byte) 182, (byte) 134, (byte) 135, (byte) 44, (byte) 87, (byte) 22, (byte) 245, (byte) 10, (byte) 248, (byte) 53, (byte) 141, (byte) 154, (byte) 139, (byte) 157, (byte) 23, (byte) 195, (byte) 64, (byte) 114, (byte) 143, (byte) 127, (byte) 135, (byte) 216, (byte) 154, (byte) 24, (byte) 216, (byte) 252, (byte) 171, (byte) 103, (byte) 173, (byte) 132, (byte) 89, (byte) 12, (byte) 46, (byte) 207, (byte) 117, (byte) 147, (byte) 57, (byte) 54, (byte) 60, (byte) 7, (byte) 3, (byte) 77, (byte) 111, (byte) 96, (byte) 111, (byte) 158, (byte) 33, (byte) 224, (byte) 84, (byte) 86, (byte) 202, (byte) 229, (byte) 233, (byte) 161 }; final byte[] e = { 1, 0, 1 }; final byte[] d = { 18, (byte) 174, (byte) 113, (byte) 164, (byte) 105, (byte) 205, (byte) 10, (byte) 43, (byte) 195, (byte) 126, (byte) 82, (byte) 108, (byte) 69, (byte) 0, (byte) 87, (byte) 31, (byte) 29, (byte) 97, (byte) 117, (byte) 29, (byte) 100, (byte) 233, (byte) 73, (byte) 112, (byte) 123, (byte) 98, (byte) 89, (byte) 15, (byte) 157, (byte) 11, (byte) 165, (byte) 124, (byte) 150, (byte) 60, (byte) 64, (byte) 30, (byte) 63, (byte) 207, (byte) 47, (byte) 44, (byte) 211, (byte) 189, (byte) 236, (byte) 136, (byte) 229, (byte) 3, (byte) 191, (byte) 198, (byte) 67, (byte) 155, (byte) 11, (byte) 40, (byte) 200, (byte) 47, (byte) 125, (byte) 55, (byte) 151, (byte) 103, (byte) 31, (byte) 82, (byte) 19, (byte) 238, (byte) 216, (byte) 193, (byte) 90, (byte) 37, (byte) 216, (byte) 213, (byte) 206, (byte) 160, (byte) 2, (byte) 94, (byte) 227, (byte) 171, (byte) 46, (byte) 139, (byte) 127, (byte) 121, (byte) 33, (byte) 111, (byte) 198, (byte) 59, (byte) 234, (byte) 86, (byte) 39, (byte) 83, (byte) 180, (byte) 6, (byte) 68, (byte) 198, (byte) 161, (byte) 81, (byte) 39, (byte) 217, (byte) 178, (byte) 149, (byte) 69, (byte) 64, (byte) 160, (byte) 187, (byte) 225, (byte) 163, (byte) 5, (byte) 86, (byte) 152, (byte) 45, (byte) 78, (byte) 159, (byte) 222, (byte) 95, (byte) 100, (byte) 37, (byte) 241, (byte) 77, (byte) 75, (byte) 113, (byte) 52, (byte) 65, (byte) 181, (byte) 93, (byte) 199, (byte) 59, (byte) 155, (byte) 74, (byte) 237, (byte) 204, (byte) 146, (byte) 172, (byte) 227, (byte) 146, (byte) 126, (byte) 55, (byte) 245, (byte) 125, (byte) 12, (byte) 253, (byte) 94, (byte) 117, (byte) 129, (byte) 250, (byte) 81, (byte) 44, (byte) 143, (byte) 73, (byte) 97, (byte) 169, (byte) 235, (byte) 11, (byte) 128, (byte) 248, (byte) 168, (byte) 7, (byte) 70, (byte) 114, (byte) 138, (byte) 85, (byte) 255, (byte) 70, (byte) 71, (byte) 31, (byte) 52, (byte) 37, (byte) 6, (byte) 59, (byte) 157, (byte) 83, (byte) 100, (byte) 47, (byte) 94, (byte) 222, (byte) 30, (byte) 132, (byte) 214, (byte) 19, (byte) 8, (byte) 26, (byte) 250, (byte) 92, (byte) 34, (byte) 208, (byte) 81, (byte) 40, (byte) 91, (byte) 214, (byte) 59, (byte) 148, (byte) 59, (byte) 86, (byte) 93, (byte) 137, (byte) 138, (byte) 5, (byte) 104, (byte) 84, (byte) 19, (byte) 229, (byte) 60, (byte) 60, (byte) 108, (byte) 101, (byte) 37, (byte) 255, (byte) 31, (byte) 227, (byte) 78, (byte) 61, (byte) 220, (byte) 112, (byte) 240, (byte) 213, (byte) 100, (byte) 80, (byte) 253, (byte) 164, (byte) 139, (byte) 161, (byte) 46, (byte) 16, (byte) 78, (byte) 157, (byte) 235, (byte) 159, (byte) 184, (byte) 24, (byte) 129, (byte) 225, (byte) 196, (byte) 189, (byte) 242, (byte) 93, (byte) 146, (byte) 71, (byte) 244, (byte) 80, (byte) 200, (byte) 101, (byte) 146, (byte) 121, (byte) 104, (byte) 231, (byte) 115, (byte) 52, (byte) 244, (byte) 65, (byte) 79, (byte) 117, (byte) 167, (byte) 80, (byte) 225, (byte) 57, (byte) 84, (byte) 110, (byte) 58, (byte) 138, (byte) 115, (byte) 157 }; BigInteger N = new BigInteger(1, n); BigInteger E = new BigInteger(1, e); BigInteger D = new BigInteger(1, d); String wrong_accessToken = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rwww"; JWS jws = new JWSReader().read(wrong_accessToken); SignatureMethod signatureMethod = new SignatureMethodRSAImpl("RS256"); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(N, E); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); Assert.assertFalse(jws.validate(signatureMethod, new PublicKey(rsaPublicKey))); }
@Test public void testValidate3() throws InvalidKeySpecException, NoSuchAlgorithmException { final byte[] n = TokenDecoder.base64DecodeToByte("n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw"); final byte[] e =TokenDecoder.base64DecodeToByte("AQAB"); final byte[] d = TokenDecoder.base64DecodeToByte("bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ"); BigInteger N = new BigInteger(1, n); BigInteger E = new BigInteger(1, e); BigInteger D = new BigInteger(1, d); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(N, E); RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(N, D); String rsa256 = "{\"kid\":\"[email protected]\", \"alg\":\"RS256\"}"; String accessToken = TokenDecoder.base64Encode(rsa256)+ "."+ "SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IH"+ "lvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBk"+ "b24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcm"+ "UgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"+ "."+ "CQKOXffDcqJ490YwuiHW7JfsLNxrRXKzCYFIDZtvznxtfxUMkcvriV4y-2_UGPqqzLNF67ps3VfI_J_OYSIfeoNfawa9bDNKtoqflRyGlDSaNIJYVjvNqVSvTFwcPcUqyVACcABosJMuAd9UWPAvNkGwRuXQEU8dD4_5KTilLbogLB4-rkQnQUq29vfA3VTOw8btMimSrsx0OrUaaOB3U9b3EpWilBEpPqndHRmgL_BPktn9gfk9xSoeGybmQGXOMZrvzH3DOAb4Ga6gzZeZImcDw5O48GiO78ARk_PJ7JXj0ebYn7m0svK-meFQRUVIfcnYxOopde9QwG6rit3Nmg"; JWS jws = new JWSReader().read(accessToken); SignatureMethod signatureMethod = new SignatureMethodRSAImpl("RS256"); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); Assert.assertTrue(jws.validate(signatureMethod, new PublicKey(rsaPublicKey))); } |
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(); } | @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()); } } |
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(); } | @Test public void testGetAccessToken() throws Exception { } |
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(); } | @Test public void testGetExpiresIn() throws Exception { } |
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(); } | @Test public void testGetRefreshToken() throws Exception { } |
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(); } | @Test public void testGetScope() throws Exception { } |
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); } | @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")); } |
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); } | @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); } |
HtmlSanitizer { public Document sanitize(String html) { Document dirtyDocument = Jsoup.parse(html); Document cleanedDocument = cleaner.clean(dirtyDocument); headCleaner.clean(dirtyDocument, cleanedDocument); return cleanedDocument; } HtmlSanitizer(); Document sanitize(String html); } | @Test public void shouldRemoveMetaRefreshBetweenHeadAndBody() { String html = "<html>" + "<head></head><meta http-equiv=\"refresh\" content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshInBody() { String html = "<html>" + "<head></head>" + "<body><meta http-equiv=\"refresh\" content=\"1; URL=http: "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshWithUpperCaseAttributeValue() { String html = "<html>" + "<head><meta http-equiv=\"REFRESH\" content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshWithMixedCaseAttributeValue() { String html = "<html>" + "<head><meta http-equiv=\"Refresh\" content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshWithoutQuotesAroundAttributeValue() { String html = "<html>" + "<head><meta http-equiv=refresh content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshWithSpacesInAttributeValue() { String html = "<html>" + "<head><meta http-equiv=\"refresh \" content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMultipleMetaRefreshTags() { String html = "<html>" + "<head><meta http-equiv=\"refresh\" content=\"1; URL=http: "<body><meta http-equiv=\"refresh\" content=\"1; URL=http: "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshButKeepOtherMetaTags() { String html = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + "<meta http-equiv=\"refresh\" content=\"1; URL=http: "</head>" + "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"></head>" + "<body>Message</body></html>", toCompactString(result)); }
@Test public void shouldProduceValidHtmlFromHtmlWithXmlDeclaration() { String html = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<html><head></head><body></body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body></body></html>", toCompactString(result)); }
@Test public void shouldNormalizeTables() { String html = "<html><head></head><body><table><tr><td></td><td></td></tr></table></body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body><table><tbody>" + "<tr><td></td><td></td></tr>" + "</tbody></table></body></html>", toCompactString(result)); }
@Test public void shouldHtmlEncodeXmlDirectives() { String html = "<html><head></head><body><table>" + "<tr><td><!==><!==>Hmailserver service shutdown:</td><td><!==><!==>Ok</td></tr>" + "</table></body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body><table><tbody>" + "<tr><td>Hmailserver service shutdown:</td><td>Ok</td></tr>" + "</tbody></table></body></html>", toCompactString(result)); }
@Test public void shouldRemoveMetaRefreshInHead() { String html = "<html>" + "<head><meta http-equiv=\"refresh\" content=\"1; URL=http: "<body>Message</body>" + "</html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>Message</body></html>", toCompactString(result)); } |
MessageDecryptVerifier { public static List<Part> findEncryptedParts(Part startPart) { List<Part> encryptedParts = new ArrayList<>(); Stack<Part> partsToCheck = new Stack<>(); partsToCheck.push(startPart); while (!partsToCheck.isEmpty()) { Part part = partsToCheck.pop(); Body body = part.getBody(); if (isPartMultipartEncrypted(part)) { encryptedParts.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 encryptedParts; } 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); } | @Test public void findEncryptedPartsShouldReturnMultipleEncryptedParts() throws Exception { MimeMessage message = new MimeMessage(); MimeMultipart multipartMixed = MimeMultipart.newInstance(); multipartMixed.setSubType("mixed"); MimeMessageHelper.setBody(message, multipartMixed); MimeMultipart multipartEncryptedOne = MimeMultipart.newInstance(); multipartEncryptedOne.setSubType("encrypted"); MimeBodyPart bodyPartOne = new MimeBodyPart(multipartEncryptedOne); setContentTypeWithProtocol(bodyPartOne, MIME_TYPE_MULTIPART_ENCRYPTED, PROTCOL_PGP_ENCRYPTED); multipartMixed.addBodyPart(bodyPartOne); MimeBodyPart bodyPartTwo = new MimeBodyPart(null, "text/plain"); multipartMixed.addBodyPart(bodyPartTwo); MimeMultipart multipartEncryptedThree = MimeMultipart.newInstance(); multipartEncryptedThree.setSubType("encrypted"); MimeBodyPart bodyPartThree = new MimeBodyPart(multipartEncryptedThree); setContentTypeWithProtocol(bodyPartThree, MIME_TYPE_MULTIPART_ENCRYPTED, PROTCOL_PGP_ENCRYPTED); multipartMixed.addBodyPart(bodyPartThree); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(2, encryptedParts.size()); assertSame(bodyPartOne, encryptedParts.get(0)); assertSame(bodyPartThree, encryptedParts.get(1)); }
@Test public void findEncrypted__withMultipartEncrypted__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(message, encryptedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubEncrypted__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubEncryptedAndEncrypted__shouldReturnBoth() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ), multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(2, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); assertSame(getPart(message, 1), encryptedParts.get(1)); }
@Test public void findEncrypted__withMultipartMixedSubTextAndEncrypted__shouldReturnEncrypted() throws Exception { Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 1), encryptedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubEncryptedAndText__shouldReturnEncrypted() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ), bodypart("text/plain") ) ); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); }
@Test public void findEncryptedPartsShouldReturnEmptyListForEmptyMessage() throws Exception { MimeMessage emptyMessage = new MimeMessage(); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(emptyMessage); assertEquals(0, encryptedParts.size()); }
@Test public void findEncryptedPartsShouldReturnEmptyListForSimpleMessage() throws Exception { MimeMessage message = new MimeMessage(); message.setBody(new TextBody("message text")); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(0, encryptedParts.size()); }
@Test public void findEncryptedPartsShouldReturnEmptyEncryptedPart() throws Exception { MimeMessage message = new MimeMessage(); MimeMultipart multipartEncrypted = MimeMultipart.newInstance(); multipartEncrypted.setSubType("encrypted"); MimeMessageHelper.setBody(message, multipartEncrypted); setContentTypeWithProtocol(message, MIME_TYPE_MULTIPART_ENCRYPTED, PROTCOL_PGP_ENCRYPTED); List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(message, encryptedParts.get(0)); } |
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); } | @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); } |
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); } | @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()); } |
TextPartFinder { @Nullable public Part findFirstTextPart(@NonNull Part part) { String mimeType = part.getMimeType(); Body body = part.getBody(); if (body instanceof Multipart) { Multipart multipart = (Multipart) body; if (isSameMimeType(mimeType, "multipart/alternative")) { return findTextPartInMultipartAlternative(multipart); } else { return findTextPartInMultipart(multipart); } } else if (isSameMimeType(mimeType, "text/plain") || isSameMimeType(mimeType, "text/html")) { return part; } return null; } @Nullable Part findFirstTextPart(@NonNull Part part); } | @Test public void findFirstTextPart_withTextPlainPart() throws Exception { Part part = createTextPart("text/plain"); Part result = textPartFinder.findFirstTextPart(part); assertEquals(part, result); }
@Test public void findFirstTextPart_withTextHtmlPart() throws Exception { Part part = createTextPart("text/html"); Part result = textPartFinder.findFirstTextPart(part); assertEquals(part, result); }
@Test public void findFirstTextPart_withoutTextPart() throws Exception { Part part = createPart("image/jpeg"); Part result = textPartFinder.findFirstTextPart(part); assertNull(result); }
@Test public void findFirstTextPart_withMultipartAlternative() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/alternative", expected, createTextPart("text/html")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartAlternativeHtmlPartFirst() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/alternative", createTextPart("text/html"), expected); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartAlternativeContainingOnlyTextHtmlPart() throws Exception { BodyPart expected = createTextPart("text/html"); Part part = createMultipart("multipart/alternative", createPart("image/gif"), expected, createTextPart("text/html")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartAlternativeNotContainingTextPart() throws Exception { Part part = createMultipart("multipart/alternative", createPart("image/gif"), createPart("application/pdf")); Part result = textPartFinder.findFirstTextPart(part); assertNull(result); }
@Test public void findFirstTextPart_withMultipartAlternativeContainingMultipartRelatedContainingTextPlain() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/alternative", createMultipart("multipart/related", expected, createPart("image/jpeg")), createTextPart("text/html")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartAlternativeContainingMultipartRelatedContainingTextHtmlFirst() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/alternative", createMultipart("multipart/related", createTextPart("text/html"), createPart("image/jpeg")), expected); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartMixedContainingTextPlain() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/mixed", createPart("image/jpeg"), expected); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartMixedContainingTextHtmlFirst() throws Exception { BodyPart expected = createTextPart("text/html"); Part part = createMultipart("multipart/mixed", expected, createTextPart("text/plain")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartMixedNotContainingTextPart() throws Exception { Part part = createMultipart("multipart/mixed", createPart("image/jpeg"), createPart("image/gif")); Part result = textPartFinder.findFirstTextPart(part); assertNull(result); }
@Test public void findFirstTextPart_withMultipartMixedContainingMultipartAlternative() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/mixed", createPart("image/jpeg"), createMultipart("multipart/alternative", expected, createTextPart("text/html")), createTextPart("text/plain")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartMixedContainingMultipartAlternativeWithTextPlainPartLast() throws Exception { BodyPart expected = createTextPart("text/plain"); Part part = createMultipart("multipart/mixed", createMultipart("multipart/alternative", createTextPart("text/html"), expected)); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartAlternativeContainingEmptyTextPlainPart() throws Exception { BodyPart expected = createEmptyPart("text/plain"); Part part = createMultipart("multipart/alternative", expected, createTextPart("text/html")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); }
@Test public void findFirstTextPart_withMultipartMixedContainingEmptyTextHtmlPart() throws Exception { BodyPart expected = createEmptyPart("text/html"); Part part = createMultipart("multipart/mixed", expected, createTextPart("text/plain")); Part result = textPartFinder.findFirstTextPart(part); assertEquals(expected, result); } |
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); } | @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()); } |
AttachmentInfoExtractor { public AttachmentViewInfo extractAttachmentInfoForDatabase(Part part) throws MessagingException { boolean isContentAvailable = part.getBody() != null; return extractAttachmentInfo(part, Uri.EMPTY, AttachmentViewInfo.UNKNOWN_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); } | @Test public void extractInfoForDb__withNoHeaders__shouldReturnEmptyValues() throws Exception { MimeBodyPart part = new MimeBodyPart(); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(Uri.EMPTY, attachmentViewInfo.internalUri); assertEquals(AttachmentViewInfo.UNKNOWN_SIZE, attachmentViewInfo.size); assertEquals("noname.txt", attachmentViewInfo.displayName); assertEquals("text/plain", attachmentViewInfo.mimeType); assertFalse(attachmentViewInfo.inlineAttachment); }
@Test public void extractInfoForDb__withTextMimeType__shouldReturnTxtExtension() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals("noname.txt", attachmentViewInfo.displayName); assertEquals("text/plain", attachmentViewInfo.mimeType); }
@Test public void extractInfoForDb__withContentTypeAndName__shouldReturnNamedAttachment() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, TEST_MIME_TYPE + "; name=\"filename.ext\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(Uri.EMPTY, attachmentViewInfo.internalUri); assertEquals(TEST_MIME_TYPE, attachmentViewInfo.mimeType); assertEquals("filename.ext", attachmentViewInfo.displayName); assertFalse(attachmentViewInfo.inlineAttachment); }
@Test public void extractInfoForDb__withContentTypeAndEncodedWordName__shouldReturnDecodedName() throws Exception { Part part = new MimeBodyPart(); part.addRawHeader(MimeHeader.HEADER_CONTENT_TYPE, MimeHeader.HEADER_CONTENT_TYPE + ": " +TEST_MIME_TYPE + "; name=\"=?ISO-8859-1?Q?Sm=F8rrebr=F8d?=\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals("Smørrebrød", attachmentViewInfo.displayName); }
@Test public void extractInfoForDb__withDispositionAttach__shouldReturnNamedAttachment() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, "attachment" + "; filename=\"filename.ext\"; meaningless=\"dummy\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(Uri.EMPTY, attachmentViewInfo.internalUri); assertEquals("filename.ext", attachmentViewInfo.displayName); assertFalse(attachmentViewInfo.inlineAttachment); }
@Test public void extractInfoForDb__withDispositionInlineAndContentId__shouldReturnInlineAttachment() throws Exception { Part part = new MimeBodyPart(); part.addRawHeader(MimeHeader.HEADER_CONTENT_ID, MimeHeader.HEADER_CONTENT_ID + ": " + TEST_CONTENT_ID); part.addRawHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, MimeHeader.HEADER_CONTENT_DISPOSITION + ": " + "inline" + ";\n filename=\"filename.ext\";\n meaningless=\"dummy\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertTrue(attachmentViewInfo.inlineAttachment); }
@Test public void extractInfoForDb__withDispositionSizeParam__shouldReturnThatSize() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, "attachment" + "; size=\"" + TEST_SIZE + "\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(TEST_SIZE, attachmentViewInfo.size); }
@Test public void extractInfoForDb__withDispositionInvalidSizeParam__shouldReturnUnknownSize() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, "attachment" + "; size=\"notanint\""); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(AttachmentViewInfo.UNKNOWN_SIZE, attachmentViewInfo.size); }
@Test public void extractInfoForDb__withNoBody__shouldReturnContentNotAvailable() throws Exception { MimeBodyPart part = new MimeBodyPart(); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertFalse(attachmentViewInfo.isContentAvailable()); }
@Test public void extractInfoForDb__withNoBody__shouldReturnContentAvailable() throws Exception { MimeBodyPart part = new MimeBodyPart(); part.setBody(new TextBody("data")); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertTrue(attachmentViewInfo.isContentAvailable()); } |
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); } | @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()); } |
EncryptionDetector { public boolean isEncrypted(@NonNull Message message) { return isPgpMimeOrSMimeEncrypted(message) || containsInlinePgpEncryptedText(message); } EncryptionDetector(TextPartFinder textPartFinder); boolean isEncrypted(@NonNull Message message); } | @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); } |
PreviewTextExtractor { @NonNull public String extractPreview(@NonNull Part textPart) throws PreviewExtractionException { String text = MessageExtractor.getTextFromPart(textPart, MAX_CHARACTERS_CHECKED_FOR_PREVIEW); if (text == null) { throw new PreviewExtractionException("Couldn't get text from part"); } String plainText = convertFromHtmlIfNecessary(textPart, text); return stripTextForPreview(plainText); } @NonNull String extractPreview(@NonNull Part textPart); } | @Test(expected = PreviewExtractionException.class) public void extractPreview_withEmptyBody_shouldThrow() throws Exception { Part part = new MimeBodyPart(null, "text/plain"); previewTextExtractor.extractPreview(part); }
@Test public void extractPreview_withSimpleTextPlain() throws Exception { String text = "The quick brown fox jumps over the lazy dog"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals(text, preview); }
@Test public void extractPreview_withSimpleTextHtml() throws Exception { String text = "<b>The quick brown fox jumps over the lazy dog</b>"; Part part = createTextPart("text/html", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("The quick brown fox jumps over the lazy dog", preview); }
@Test public void extractPreview_withLongTextPlain() throws Exception { String text = "" + "10--------20--------30--------40--------50--------" + "60--------70--------80--------90--------100-------" + "110-------120-------130-------140-------150-------" + "160-------170-------180-------190-------200-------" + "210-------220-------230-------240-------250-------" + "260-------270-------280-------290-------300-------" + "310-------320-------330-------340-------350-------" + "360-------370-------380-------390-------400-------" + "410-------420-------430-------440-------450-------" + "460-------470-------480-------490-------500-------" + "510-------520-------"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals(text.substring(0, 511) + "…", preview); }
@Test public void extractPreview_shouldStripSignature() throws Exception { String text = "" + "Some text\r\n" + "-- \r\n" + "Signature"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("Some text", preview); }
@Test public void extractPreview_shouldStripHorizontalLine() throws Exception { String text = "" + "line 1\r\n" + "----\r\n" + "line 2"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("line 1 line 2", preview); }
@Test public void extractPreview_shouldStripQuoteHeaderAndQuotedText() throws Exception { String text = "" + "some text\r\n" + "On 01/02/03 someone wrote\r\n" + "> some quoted text\r\n" + "# some other quoted text\r\n"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("some text", preview); }
@Test public void extractPreview_shouldStripGenericQuoteHeader() throws Exception { String text = "" + "Am 13.12.2015 um 23:42 schrieb Hans:\r\n" + "> hallo\r\n" + "hi there\r\n"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("hi there", preview); }
@Test public void extractPreview_shouldStripHorizontalRules() throws Exception { String text = "line 1" + "------------------------------\r\n" + "line 2"; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("line 1 line 2", preview); }
@Test public void extractPreview_shouldReplaceUrl() throws Exception { String text = "some url: https: Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("some url: ...", preview); }
@Test public void extractPreview_shouldCollapseAndTrimWhitespace() throws Exception { String text = " whitespace is\t\tfun "; Part part = createTextPart("text/plain", text); String preview = previewTextExtractor.extractPreview(part); assertEquals("whitespace is fun", preview); } |
PgpMessageBuilder extends MessageBuilder { public void setCryptoStatus(ComposeCryptoStatus cryptoStatus) { this.cryptoStatus = cryptoStatus; } @VisibleForTesting PgpMessageBuilder(Context context, MessageIdGenerator messageIdGenerator, BoundaryGenerator boundaryGenerator,
AutocryptOperations autocryptOperations, AutocryptOpenPgpApiInteractor autocryptOpenPgpApiInteractor); static PgpMessageBuilder newInstance(); void setOpenPgpApi(OpenPgpApi openPgpApi); @Override void buildMessageOnActivityResult(int requestCode, @NonNull Intent userInteractionResult); void setCryptoStatus(ComposeCryptoStatus cryptoStatus); } | @Test public void build__withCryptoProviderUnconfigured__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setCryptoProviderState(CryptoProviderState.UNCONFIGURED); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void build__withCryptoProviderUninitialized__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setCryptoProviderState(CryptoProviderState.UNINITIALIZED); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void build__withCryptoProviderError__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setCryptoProviderState(CryptoProviderState.ERROR); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void build__withCryptoProviderLostConnection__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setCryptoProviderState(CryptoProviderState.LOST_CONNECTION); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void buildCleartext__withNoSigningKey__shouldBuildTrivialMessage() { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setOpenPgpKeyId(null); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); assertEquals("text/plain", message.getMimeType()); }
@Test public void buildCleartext__shouldSucceed() { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL); }
@Test public void buildSign__withNoDetachedSignatureInResult__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void buildSign__withDetachedSignatureInResult__shouldSucceed() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); ArgumentCaptor<Intent> capturedApiIntent = ArgumentCaptor.forClass(Intent.class); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); returnIntent.putExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE, new byte[] { 1, 2, 3 }); when(openPgpApi.executeApi(capturedApiIntent.capture(), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); Intent expectedIntent = new Intent(OpenPgpApi.ACTION_DETACHED_SIGN); expectedIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID); expectedIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); assertIntentEqualsActionAndExtras(expectedIntent, capturedApiIntent.getValue()); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); Assert.assertEquals("message must be multipart/signed", "multipart/signed", message.getMimeType()); MimeMultipart multipart = (MimeMultipart) message.getBody(); Assert.assertEquals("multipart/signed must consist of two parts", 2, multipart.getCount()); BodyPart contentBodyPart = multipart.getBodyPart(0); Assert.assertEquals("first part must have content type text/plain", "text/plain", MimeUtility.getHeaderParameter(contentBodyPart.getContentType(), null)); assertTrue("signed message body must be TextBody", contentBodyPart.getBody() instanceof TextBody); Assert.assertEquals(MimeUtil.ENC_QUOTED_PRINTABLE, ((TextBody) contentBodyPart.getBody()).getEncoding()); assertContentOfBodyPartEquals("content must match the message text", contentBodyPart, TEST_MESSAGE_TEXT); BodyPart signatureBodyPart = multipart.getBodyPart(1); String contentType = signatureBodyPart.getContentType(); Assert.assertEquals("second part must be pgp signature", "application/pgp-signature", MimeUtility.getHeaderParameter(contentType, null)); Assert.assertEquals("second part must be called signature.asc", "signature.asc", MimeUtility.getHeaderParameter(contentType, "name")); assertContentOfBodyPartEquals("content must match the supplied detached signature", signatureBodyPart, new byte[] { 1, 2, 3 }); assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL); }
@Test public void buildSign__withUserInteractionResult__shouldReturnUserInteraction() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Intent returnIntent = mock(Intent.class); when(returnIntent.getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt())) .thenReturn(OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); final PendingIntent mockPendingIntent = mock(PendingIntent.class); when(returnIntent.getParcelableExtra(eq(OpenPgpApi.RESULT_INTENT))) .thenReturn(mockPendingIntent); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); ArgumentCaptor<PendingIntent> captor = ArgumentCaptor.forClass(PendingIntent.class); verify(mockCallback).onMessageBuildReturnPendingIntent(captor.capture(), anyInt()); verifyNoMoreInteractions(mockCallback); PendingIntent pendingIntent = captor.getValue(); Assert.assertSame(pendingIntent, mockPendingIntent); }
@Test public void buildSign__withReturnAfterUserInteraction__shouldSucceed() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); int returnedRequestCode; { Intent returnIntent = spy(new Intent()); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); PendingIntent mockPendingIntent = mock(PendingIntent.class); when(returnIntent.getParcelableExtra(eq(OpenPgpApi.RESULT_INTENT))) .thenReturn(mockPendingIntent); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(returnIntent).getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt()); ArgumentCaptor<PendingIntent> piCaptor = ArgumentCaptor.forClass(PendingIntent.class); ArgumentCaptor<Integer> rcCaptor = ArgumentCaptor.forClass(Integer.class); verify(mockCallback).onMessageBuildReturnPendingIntent(piCaptor.capture(), rcCaptor.capture()); verifyNoMoreInteractions(mockCallback); returnedRequestCode = rcCaptor.getValue(); Assert.assertSame(mockPendingIntent, piCaptor.getValue()); } { Intent returnIntent = spy(new Intent()); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); Intent mockReturnIntent = mock(Intent.class); when(openPgpApi.executeApi(same(mockReturnIntent), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.onActivityResult(returnedRequestCode, Activity.RESULT_OK, mockReturnIntent, mockCallback); verify(openPgpApi).executeApi(same(mockReturnIntent), any(OpenPgpDataSource.class), any(OutputStream.class)); verify(returnIntent).getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt()); } }
@Test public void buildEncrypt__withoutRecipients__shouldThrow() throws MessagingException { cryptoStatusBuilder .setCryptoMode(CryptoMode.CHOICE_ENABLED) .setRecipients(new ArrayList<Recipient>()); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Intent returnIntent = spy(new Intent()); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); }
@Test public void buildEncrypt__shouldSucceed() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.CHOICE_ENABLED) .setRecipients(Collections.singletonList(new Recipient("test", "[email protected]", "labru", -1, "key"))) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); ArgumentCaptor<Intent> capturedApiIntent = ArgumentCaptor.forClass(Intent.class); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(capturedApiIntent.capture(), any(OpenPgpDataSource.class), any(OutputStream.class))).thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); Intent expectedApiIntent = new Intent(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, new long[] { TEST_KEY_ID }); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.getRecipientAddresses()); assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.getValue()); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); Assert.assertEquals("message must be multipart/encrypted", "multipart/encrypted", message.getMimeType()); MimeMultipart multipart = (MimeMultipart) message.getBody(); Assert.assertEquals("multipart/encrypted must consist of two parts", 2, multipart.getCount()); BodyPart dummyBodyPart = multipart.getBodyPart(0); Assert.assertEquals("first part must be pgp encrypted dummy part", "application/pgp-encrypted", dummyBodyPart.getContentType()); assertContentOfBodyPartEquals("content must match the supplied detached signature", dummyBodyPart, "Version: 1"); BodyPart encryptedBodyPart = multipart.getBodyPart(1); Assert.assertEquals("second part must be octet-stream of encrypted data", "application/octet-stream; name=\"encrypted.asc\"", encryptedBodyPart.getContentType()); assertTrue("message body must be BinaryTempFileBody", encryptedBodyPart.getBody() instanceof BinaryTempFileBody); Assert.assertEquals(MimeUtil.ENC_7BIT, ((BinaryTempFileBody) encryptedBodyPart.getBody()).getEncoding()); assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL); }
@Test public void buildEncrypt__withInlineEnabled__shouldSucceed() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.CHOICE_ENABLED) .setRecipients(Collections.singletonList(new Recipient("test", "[email protected]", "labru", -1, "key"))) .setEnablePgpInline(true) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); ArgumentCaptor<Intent> capturedApiIntent = ArgumentCaptor.forClass(Intent.class); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(capturedApiIntent.capture(), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); Intent expectedApiIntent = new Intent(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, new long[] { TEST_KEY_ID }); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.getRecipientAddresses()); assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.getValue()); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); Assert.assertEquals("text/plain", message.getMimeType()); assertTrue("message body must be BinaryTempFileBody", message.getBody() instanceof BinaryTempFileBody); Assert.assertEquals(MimeUtil.ENC_7BIT, ((BinaryTempFileBody) message.getBody()).getEncoding()); assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL); }
@Test public void buildSign__withInlineEnabled__shouldSucceed() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.SIGN_ONLY) .setRecipients(Collections.singletonList(new Recipient("test", "[email protected]", "labru", -1, "key"))) .setEnablePgpInline(true) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); ArgumentCaptor<Intent> capturedApiIntent = ArgumentCaptor.forClass(Intent.class); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(capturedApiIntent.capture(), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); Intent expectedApiIntent = new Intent(OpenPgpApi.ACTION_SIGN); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID); expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.getValue()); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); Assert.assertEquals("message must be text/plain", "text/plain", message.getMimeType()); assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL); }
@Test public void buildSignWithAttach__withInlineEnabled__shouldThrow() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.SIGN_ONLY) .setEnablePgpInline(true) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); pgpMessageBuilder.setAttachments(Collections.singletonList(Attachment.createAttachment(null, 0, null))); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); verifyNoMoreInteractions(openPgpApi); }
@Test public void buildEncryptWithAttach__withInlineEnabled__shouldThrow() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.CHOICE_ENABLED) .setEnablePgpInline(true) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); pgpMessageBuilder.setAttachments(Collections.singletonList(Attachment.createAttachment(null, 0, null))); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); verifyNoMoreInteractions(openPgpApi); }
@Test public void buildOpportunisticEncrypt__withNoKeysAndNoSignOnly__shouldNotBeSigned() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setRecipients(Collections.singletonList(new Recipient("test", "[email protected]", "labru", -1, "key"))) .setCryptoMode(CryptoMode.NO_CHOICE) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); Intent returnIntent = new Intent(); returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); returnIntent.putExtra(OpenPgpApi.RESULT_ERROR, new OpenPgpError(OpenPgpError.OPPORTUNISTIC_MISSING_KEYS, "Missing keys")); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntent); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class); verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)); verifyNoMoreInteractions(mockCallback); MimeMessage message = captor.getValue(); Assert.assertEquals("text/plain", message.getMimeType()); }
@Test public void buildSign__withNoDetachedSignatureExtra__shouldFail() throws MessagingException { ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder .setCryptoMode(CryptoMode.SIGN_ONLY) .build(); pgpMessageBuilder.setCryptoStatus(cryptoStatus); Intent returnIntentSigned = new Intent(); returnIntentSigned.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))) .thenReturn(returnIntentSigned); Callback mockCallback = mock(Callback.class); pgpMessageBuilder.buildAsync(mockCallback); verify(mockCallback).onMessageBuildException(any(MessagingException.class)); verifyNoMoreInteractions(mockCallback); } |
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); } | @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)); } |
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); } | @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); } |
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); } | @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); } |
UidReverseComparator implements Comparator<Message> { @Override public int compare(Message messageLeft, Message messageRight) { Long uidLeft = getUidForMessage(messageLeft); Long uidRight = getUidForMessage(messageRight); if (uidLeft == null && uidRight == null) { return 0; } else if (uidLeft == null) { return 1; } else if (uidRight == null) { return -1; } return uidRight.compareTo(uidLeft); } @Override int compare(Message messageLeft, Message messageRight); } | @Test public void compare_withTwoNullArguments_shouldReturnZero() throws Exception { Message messageLeft = null; Message messageRight = null; int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are null", 0, result); }
@Test public void compare_withNullArgumentAndMessageWithNullUid_shouldReturnZero() throws Exception { Message messageLeft = null; Message messageRight = createMessageWithNullUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withMessageWithNullUidAndNullArgument_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithNullUid(); Message messageRight = null; int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withTwoMessagesWithNullUid_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithNullUid(); Message messageRight = createMessageWithNullUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are a message with a null UID", 0, result); }
@Test public void compare_withNullArgumentAndMessageWithInvalidUid_shouldReturnZero() throws Exception { Message messageLeft = null; Message messageRight = createMessageWithInvalidUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withMessageWithInvalidUidAndNullArgument_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithInvalidUid(); Message messageRight = null; int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withTwoMessagesWithInvalidUid_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithInvalidUid(); Message messageRight = createMessageWithInvalidUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are a message with an invalid UID", 0, result); }
@Test public void compare_withMessageWithNullUidAndMessageWithInvalidUid_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithNullUid(); Message messageRight = createMessageWithInvalidUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withMessageWithInvalidUidAndMessageWithNullUid_shouldReturnZero() throws Exception { Message messageLeft = createMessageWithInvalidUid(); Message messageRight = createMessageWithNullUid(); int result = comparator.compare(messageLeft, messageRight); assertEquals("result must be 0 when both arguments are not a message with valid UID", 0, result); }
@Test public void compare_withLeftNullArgument_shouldReturnPositive() throws Exception { Message messageLeft = null; Message messageRight = createMessageWithUid(1); int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be > 0 when left argument is null", result > 0); }
@Test public void compare_withLeftMessageWithNullUid_shouldReturnPositive() throws Exception { Message messageLeft = createMessageWithNullUid(); Message messageRight = createMessageWithUid(1); int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be > 0 when left argument is message with null UID", result > 0); }
@Test public void compare_withLeftMessageWithInvalidUid_shouldReturnPositive() throws Exception { Message messageLeft = createMessageWithInvalidUid(); Message messageRight = createMessageWithUid(1); int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be > 0 when left argument is message with invalid UID", result > 0); }
@Test public void compare_withRightNullArgument_shouldReturnNegative() throws Exception { Message messageLeft = createMessageWithUid(1); Message messageRight = null; int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be < 0 when right argument is null", result < 0); }
@Test public void compare_withRightMessageWithNullUid_shouldReturnNegative() throws Exception { Message messageLeft = createMessageWithUid(1); Message messageRight = createMessageWithNullUid(); int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be < 0 when right argument is message with null UID", result < 0); }
@Test public void compare_withRightMessageWithInvalidUid_shouldReturnNegative() throws Exception { Message messageLeft = createMessageWithUid(1); Message messageRight = createMessageWithInvalidUid(); int result = comparator.compare(messageLeft, messageRight); assertTrue("result must be < 0 when right argument is message with invalid UID", result < 0); }
@Test public void compare_twoMessages_shouldReturnOrderByUid() throws Exception { Message messageSmall = createMessageWithUid(5); Message messageLarge = createMessageWithUid(15); int resultOne = comparator.compare(messageSmall, messageLarge); int resultTwo = comparator.compare(messageLarge, messageSmall); assertTrue("result must be > 0 when right message has larger UID than left message", resultOne > 0); assertTrue("result must be < 0 when left message has larger UID than right message", resultTwo < 0); } |
MessagingController { @VisibleForTesting protected void clearFolderSynchronous(Account account, String folderId, MessagingListener listener) { LocalFolder localFolder = null; try { localFolder = account.getLocalStore().getFolder(folderId); localFolder.open(Folder.OPEN_MODE_RW); localFolder.clearAllMessages(); } catch (UnavailableStorageException e) { Timber.i("Failed to clear folder because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Timber.e(e, "clearFolder failed"); } finally { closeFolder(localFolder); } listFoldersSynchronous(account, false, listener); } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void clearFolderSynchronous_shouldOpenFolderForWriting() throws MessagingException { controller.clearFolderSynchronous(account, FOLDER_ID, listener); verify(localFolder).open(Folder.OPEN_MODE_RW); }
@Test public void clearFolderSynchronous_shouldClearAllMessagesInTheFolder() throws MessagingException { controller.clearFolderSynchronous(account, FOLDER_ID, listener); verify(localFolder).clearAllMessages(); }
@Test public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException { controller.clearFolderSynchronous(account, FOLDER_ID, listener); verify(localFolder, atLeastOnce()).close(); }
@Test(expected = UnavailableAccountException.class) public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException { doThrow(new UnavailableStorageException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); controller.clearFolderSynchronous(account, FOLDER_ID, listener); }
@Test() public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException { doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW); try { controller.clearFolderSynchronous(account, FOLDER_ID, listener); } catch (Exception ignored){ } verify(localFolder, atLeastOnce()).close(); }
@Test() public void clearFolderSynchronous_shouldListFolders() throws MessagingException { controller.clearFolderSynchronous(account, FOLDER_ID, listener); verify(listener, atLeastOnce()).listFoldersStarted(account); } |
MessagingController { public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } List<LocalFolder> localFolders = null; if (!account.isAvailable(context)) { Timber.i("not listing folders of unavailable account"); } else { try { LocalStore localStore = account.getLocalStore(); localFolders = localStore.getFolders(false); if (refreshRemote || localFolders.isEmpty()) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, localFolders); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { Timber.w(e, "Failed to list folders"); l.listFoldersFailed(account, e.getMessage()); } return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void listFoldersSynchronous_shouldNotifyTheListenerListingStarted() throws MessagingException { List<LocalFolder> folders = Collections.singletonList(localFolder); when(localStore.getFolders(false)).thenReturn(folders); controller.listFoldersSynchronous(account, false, listener); verify(listener).listFoldersStarted(account); }
@Test public void listFoldersSynchronous_shouldNotifyFailureOnException() throws MessagingException { when(localStore.getFolders(false)).thenThrow(new MessagingException("Test")); controller.listFoldersSynchronous(account, true, listener); verify(listener).listFoldersFailed(account, "Test"); }
@Test public void listFoldersSynchronous_shouldNotNotifyFinishedAfterFailure() throws MessagingException { when(localStore.getFolders(false)).thenThrow(new MessagingException("Test")); controller.listFoldersSynchronous(account, true, listener); verify(listener, never()).listFoldersFinished(account); }
@Test public void listFoldersSynchronous_shouldNotifyFinishedAfterSuccess() throws MessagingException { List<LocalFolder> folders = Collections.singletonList(localFolder); when(localStore.getFolders(false)).thenReturn(folders); controller.listFoldersSynchronous(account, false, listener); verify(listener).listFoldersFinished(account); } |
MessagingController { @VisibleForTesting void refreshRemoteSynchronous(final Account account, final MessagingListener listener) { List<LocalFolder> localFolders = null; try { Store store = account.getRemoteStore(); List<? extends Folder> remoteFolders = store.getFolders(false); LocalStore localStore = account.getLocalStore(); Map<String, Folder> remoteFolderMap = new HashMap<>(); List<LocalFolder> foldersToCreate = new LinkedList<>(); localFolders = localStore.getFolders(false); Set<String> localFolderIds = new HashSet<>(); for (Folder localFolder : localFolders) { localFolderIds.add(localFolder.getId()); } for (Folder remoteFolder : remoteFolders) { if (!localFolderIds.contains(remoteFolder.getId())) { LocalFolder localFolder = localStore.getFolder(remoteFolder.getId()); foldersToCreate.add(localFolder); } remoteFolderMap.put(remoteFolder.getId(), remoteFolder); } localStore.createFolders(foldersToCreate, account.getDisplayCount()); localFolders = localStore.getFolders(false); for (LocalFolder localFolder : localFolders) { String localFolderId = localFolder.getId(); if (QMail.FOLDER_NONE.equals(localFolderId)) { localFolder.delete(false); } if (!account.isSpecialFolder(localFolderId) && !remoteFolderMap.containsKey(localFolderId)) { localFolder.delete(false); } } localFolders = localStore.getFolders(false); for (LocalFolder localFolder : localFolders) { String localFolderId = localFolder.getId(); if (remoteFolderMap.containsKey(localFolderId)) { localFolder.setName(remoteFolderMap.get(localFolderId).getName()); localFolder.setParentId(remoteFolderMap.get(localFolderId).getParentId()); } } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, localFolders); } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { Timber.w(e, "Unable to list folders"); l.listFoldersFailed(account, ""); } Timber.e(e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void refreshRemoteSynchronous_shouldNotDeleteFoldersOnRemote() throws MessagingException { configureRemoteStoreWithFolder(); when(localStore.getFolders(false)) .thenReturn(Collections.singletonList(localFolder)); List<Folder> folders = Collections.singletonList(remoteFolder); when(remoteStore.getFolders(false)).thenAnswer(createAnswer(folders)); controller.refreshRemoteSynchronous(account, listener); verify(localFolder, never()).delete(false); }
@Test public void refreshRemoteSynchronous_shouldNotifyFinishedAfterSuccess() throws MessagingException { configureRemoteStoreWithFolder(); List<LocalFolder> folders = Collections.singletonList(localFolder); when(localStore.getFolders(false)).thenReturn(folders); controller.refreshRemoteSynchronous(account, listener); verify(listener).listFoldersFinished(account); }
@Test public void refreshRemoteSynchronous_shouldNotNotifyFinishedAfterFailure() throws MessagingException { configureRemoteStoreWithFolder(); when(localStore.getFolders(false)).thenThrow(new MessagingException("Test")); controller.refreshRemoteSynchronous(account, listener); verify(listener, never()).listFoldersFinished(account); } |
MessagingController { @VisibleForTesting void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) { final AccountStats stats = new AccountStats(); final Set<String> uuidSet = new HashSet<>(Arrays.asList(search.getAccountUuids())); List<Account> accounts = Preferences.getPreferences(context).getAccounts(); boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS); for (final Account account : accounts) { if (!allAccounts && !uuidSet.contains(account.getUuid())) { continue; } MessageRetrievalListener<LocalMessage> retrievalListener = new MessageRetrievalListener<LocalMessage>() { @Override public void messageStarted(String message, int number, int ofTotal) { } @Override public void messagesFinished(int number) { } @Override public void messageFinished(LocalMessage message, int number, int ofTotal) { if (!isMessageSuppressed(message)) { List<LocalMessage> messages = new ArrayList<>(); messages.add(message); stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, null, messages); } } } }; try { LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, search); } catch (Exception e) { Timber.e(e); } } if (listener != null) { listener.searchStats(stats); } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void searchLocalMessagesSynchronous_shouldCallSearchForMessagesOnLocalStore() throws Exception { setAccountsInPreferences(Collections.singletonMap("1", account)); when(search.getAccountUuids()).thenReturn(new String[]{"allAccounts"}); controller.searchLocalMessagesSynchronous(search, listener); verify(localStore).searchForMessages(any(MessageRetrievalListener.class), eq(search)); }
@Test public void searchLocalMessagesSynchronous_shouldNotifyWhenStoreFinishesRetrievingAMessage() throws Exception { setAccountsInPreferences(Collections.singletonMap("1", account)); LocalMessage localMessage = mock(LocalMessage.class); when(localMessage.getFolder()).thenReturn(localFolder); when(search.getAccountUuids()).thenReturn(new String[]{"allAccounts"}); when(localStore.searchForMessages(any(MessageRetrievalListener.class), eq(search))) .thenThrow(new MessagingException("Test")); controller.searchLocalMessagesSynchronous(search, listener); verify(localStore).searchForMessages(messageRetrievalListenerCaptor.capture(), eq(search)); messageRetrievalListenerCaptor.getValue().messageFinished(localMessage, 1, 1); verify(listener).listLocalMessagesAddMessages(eq(account), eq((String) null), eq((String) null), eq(Collections.singletonList(localMessage))); } |
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); } | @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)); } |
MessagingController { @VisibleForTesting void searchRemoteMessagesSynchronous(final String acctUuid, final String folderId, final String folderName, final String query, final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) { final Account acct = Preferences.getPreferences(context).getAccount(acctUuid); if (listener != null) { listener.remoteSearchStarted(folderId, folderName); } List<Message> extraResults = new ArrayList<>(); try { Store remoteStore = acct.getRemoteStore(); LocalStore localStore = acct.getLocalStore(); if (remoteStore == null || localStore == null) { throw new MessagingException("Could not get store"); } Folder remoteFolder = remoteStore.getFolder(folderId); LocalFolder localFolder = localStore.getFolder(folderId); if (remoteFolder == null || localFolder == null) { throw new MessagingException("Folder not found"); } List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags); Timber.i("Remote search got %d results", messages.size()); List<Message> remoteMessages = localFolder.extractNewMessages(messages); messages.clear(); if (listener != null) { listener.remoteSearchServerQueryComplete(folderId, folderName, remoteMessages.size(), acct.getRemoteSearchNumResults()); } Collections.sort(remoteMessages, new UidReverseComparator()); int resultLimit = acct.getRemoteSearchNumResults(); if (resultLimit > 0 && remoteMessages.size() > resultLimit) { extraResults = remoteMessages.subList(resultLimit, remoteMessages.size()); remoteMessages = remoteMessages.subList(0, resultLimit); } loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener); } catch (Exception e) { if (Thread.currentThread().isInterrupted()) { Timber.i(e, "Caught exception on aborted remote search; safe to ignore."); } else { Timber.e(e, "Could not complete remote search"); if (listener != null) { listener.remoteSearchFailed(null, null, e.getMessage()); } Timber.e(e); } } finally { if (listener != null) { listener.remoteSearchFinished(folderId, folderName, 0, acct.getRemoteSearchNumResults(), extraResults); } } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void searchRemoteMessagesSynchronous_shouldNotifyStartedListingRemoteMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(listener).remoteSearchStarted(FOLDER_ID, FOLDER_NAME); }
@Test public void searchRemoteMessagesSynchronous_shouldQueryRemoteFolder() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(remoteFolder).search("query", reqFlags, forbiddenFlags); }
@Test public void searchRemoteMessagesSynchronous_shouldAskLocalFolderToDetermineNewMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(localFolder).extractNewMessages(remoteMessages); }
@Test public void searchRemoteMessagesSynchronous_shouldTryAndGetNewMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(localFolder).getMessage("newMessageUid1"); }
@Test public void searchRemoteMessagesSynchronous_shouldNotTryAndGetOldMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(localFolder, never()).getMessage("oldMessageUid"); }
@Test public void searchRemoteMessagesSynchronous_shouldFetchNewMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(remoteFolder, times(2)).fetch(eq(Collections.singletonList(remoteNewMessage2)), fetchProfileCaptor.capture(), Matchers.<MessageRetrievalListener>eq(null)); }
@Test public void searchRemoteMessagesSynchronous_shouldNotFetchExistingMessages() throws Exception { setupRemoteSearch(); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(remoteFolder, never()).fetch(eq(Collections.singletonList(remoteNewMessage1)), fetchProfileCaptor.capture(), Matchers.<MessageRetrievalListener>eq(null)); }
@Test public void searchRemoteMessagesSynchronous_shouldNotifyOnFailure() throws Exception { setupRemoteSearch(); when(account.getRemoteStore()).thenThrow(new MessagingException("Test")); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(listener).remoteSearchFailed(null, null, "Test"); }
@Test public void searchRemoteMessagesSynchronous_shouldNotifyOnFinish() throws Exception { setupRemoteSearch(); when(account.getRemoteStore()).thenThrow(new MessagingException("Test")); controller.searchRemoteMessagesSynchronous("1", FOLDER_ID, FOLDER_NAME, "query", reqFlags, forbiddenFlags, listener); verify(listener).remoteSearchFinished(FOLDER_ID, FOLDER_NAME, 0, 50, Collections.<Message>emptyList()); } |
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); } | @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)); } |
MessagingController { @VisibleForTesting protected void sendPendingMessagesSynchronous(final Account account) { LocalFolder localOutboxFolder = null; Exception lastFailure = null; boolean wasPermanentFailure = false; try { LocalStore localStore = account.getLocalStore(); localOutboxFolder = localStore.getFolder( account.getOutboxFolderId()); String sentFolderId = account.getSentFolderId(); LocalFolder localSentFolder = localStore.getFolder(sentFolderId); String sentFolderName = localSentFolder != null ? localSentFolder.getName() : sentFolderId; if (!localOutboxFolder.exists()) { Timber.v("Outbox does not exist"); return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localOutboxFolder.open(Folder.OPEN_MODE_RW); List<LocalMessage> localMessages = localOutboxFolder.getMessages(null); int progress = 0; int todo = localMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, sentFolderId, sentFolderName, progress, todo); } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); Timber.i("Scanning folder '%s' (%d) for messages to send", account.getOutboxFolderId(), localOutboxFolder.getDatabaseId()); Transport transport = transportProvider.getTransport(QMail.app, account); for (LocalMessage message : localMessages) { if (message.isSet(Flag.DELETED)) { message.destroy(); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } Timber.i("Send count for message %s is %d", message.getUid(), count.get()); if (count.incrementAndGet() > QMail.MAX_SEND_ATTEMPTS) { Timber.e("Send count for message %s can't be delivered after %d attempts. " + "Giving up until the user restarts the device", message.getUid(), MAX_SEND_ATTEMPTS); notificationController.showSendFailedNotification(account, new MessagingException(message.getSubject())); continue; } localOutboxFolder.fetch(Collections.singletonList(message), fp, null); try { if (message.getHeader(QMail.IDENTITY_HEADER).length > 0) { Timber.v("The user has set the Outbox and Drafts folder to the same thing. " + "This message appears to be a draft, so K-9 will not send it"); continue; } message.setFlag(Flag.X_SEND_IN_PROGRESS, true); Timber.i("Sending message with UID %s", message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, sentFolderId, sentFolderName, progress, todo); } moveOrDeleteSentMessage(account, localStore, localOutboxFolder, message); } catch (AuthenticationFailedException e) { lastFailure = e; wasPermanentFailure = false; handleAuthenticationFailure(account, false); handleSendFailure(account, localStore, localOutboxFolder, message, e, wasPermanentFailure); } catch (CertificateValidationException e) { lastFailure = e; wasPermanentFailure = false; notifyUserIfCertificateProblem(account, e, false); handleSendFailure(account, localStore, localOutboxFolder, message, e, wasPermanentFailure); } catch (MessagingException e) { lastFailure = e; wasPermanentFailure = e.isPermanentFailure(); handleSendFailure(account, localStore, localOutboxFolder, message, e, wasPermanentFailure); } catch (Exception e) { lastFailure = e; wasPermanentFailure = true; handleSendFailure(account, localStore, localOutboxFolder, message, e, wasPermanentFailure); } } catch (Exception e) { lastFailure = e; wasPermanentFailure = false; Timber.e(e, "Failed to fetch message for sending"); notifySynchronizeMailboxFailed(account, localOutboxFolder, e); } } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (lastFailure != null) { if (wasPermanentFailure) { notificationController.showSendFailedNotification(account, lastFailure); } else { notificationController.showSendFailedNotification(account, lastFailure); } } } catch (UnavailableStorageException e) { Timber.i("Failed to send pending messages because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Timber.v(e, "Failed to send pending messages"); for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } } finally { if (lastFailure == null) { notificationController.clearSendFailedNotification(account); } closeFolder(localOutboxFolder); } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void sendPendingMessagesSynchronous_shouldCallListenerOnStart() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).sendPendingMessagesStarted(account); }
@Test public void sendPendingMessagesSynchronous_shouldSetProgress() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).synchronizeMailboxProgress(account, "SentID", "Sent", 0, 1); }
@Test public void sendPendingMessagesSynchronous_whenMessageSentSuccesfully_shouldUpdateProgress() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).synchronizeMailboxProgress(account, "SentID", "Sent", 1, 1); }
@Test public void sendPendingMessagesSynchronous_shouldUpdateProgress() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).synchronizeMailboxProgress(account, "SentID", "Sent", 1, 1); }
@Test public void sendPendingMessagesSynchronous_shouldCallListenerOnCompletion() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).sendPendingMessagesCompleted(account); } |
MessagingController { @VisibleForTesting void synchronizeMailboxSynchronous(final Account account, final String folderId, final String folderName, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; Timber.i("Synchronizing folder %s:%s", account.getDescription(), folderId); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folderId, folderName); } if (folderId.equals(account.getOutboxFolderId())) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folderId, folderName, 0, 0); } return; } Exception commandException = null; try { Timber.d("SYNC: About to process pending commands for account %s", account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { Timber.e(e, "Failure processing command, but allow message sync attempt"); commandException = e; } Timber.v("SYNC: About to get local folder %s", folderId); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folderId); final LocalFolder localFolder = tLocalFolder; localFolder.open(Folder.OPEN_MODE_RW); localFolder.updateLastUid(); Map<String, Long> localUidMap = localFolder.getAllMessagesAndEffectiveDates(); if (providedRemoteFolder != null) { Timber.v("SYNC: using providedRemoteFolder %s", folderId); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); Timber.v("SYNC: About to get remote folder %s", folderId); remoteFolder = remoteStore.getFolder(folderId); if (!verifyOrCreateRemoteSpecialFolder(account, folderId, folderName, remoteFolder, listener)) { return; } Timber.v("SYNC: About to open remote folder %s", folderId); if (Expunge.EXPUNGE_ON_POLL == account.getExpungePolicy()) { Timber.d("SYNC: Expunging folder %s:%s", account.getDescription(), folderId); remoteFolder.expunge(); } remoteFolder.open(Folder.OPEN_MODE_RO); } notificationController.clearAuthenticationErrorNotification(account, true); int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); if (visibleLimit < 0) { visibleLimit = QMail.DEFAULT_VISIBLE_LIMIT; } final List<Message> remoteMessages = new ArrayList<>(); Map<String, Message> remoteUidMap = new HashMap<>(); Timber.v("SYNC: Remote message count for folder %s is %d", folderId, remoteMessageCount); final Date earliestDate = account.getEarliestPollDate(); long earliestTimestamp = earliestDate != null ? earliestDate.getTime() : 0L; int remoteStart = 1; if (remoteMessageCount > 0) { if (visibleLimit > 0) { remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; } else { remoteStart = 1; } Timber.v("SYNC: About to get messages %d through %d for folder %s", remoteStart, remoteMessageCount, folderId); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folderId, folderName); } List<? extends Message> remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteMessageCount, earliestDate, null); int messageCount = remoteMessageArray.size(); for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folderId, folderName, headerProgress.get(), messageCount); } Long localMessageTimestamp = localUidMap.get(thisMess.getUid()); if (localMessageTimestamp == null || localMessageTimestamp >= earliestTimestamp) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } Timber.v("SYNC: Got %d messages for folder %s", remoteUidMap.size(), folderId); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folderId, folderName, headerProgress.get(), remoteUidMap.size()); } } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folderId); } MoreMessages moreMessages = localFolder.getMoreMessages(); if (account.syncRemoteDeletions()) { List<String> destroyMessageUids = new ArrayList<>(); for (String localMessageUid : localUidMap.keySet()) { if (remoteUidMap.get(localMessageUid) == null) { destroyMessageUids.add(localMessageUid); } } List<LocalMessage> destroyMessages = localFolder.getMessagesByUids(destroyMessageUids); if (!destroyMessageUids.isEmpty()) { moreMessages = MoreMessages.UNKNOWN; localFolder.destroyMessages(destroyMessages); for (Message destroyMessage : destroyMessages) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folderId, folderName, destroyMessage); } } } } localUidMap = null; if (moreMessages == MoreMessages.UNKNOWN) { updateMoreMessages(remoteFolder, localFolder, earliestDate, remoteStart); } int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false, true); int unreadMessageCount = localFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderId, folderName, unreadMessageCount); } localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); Timber.d("Done synchronizing folder %s:%s @ %tc with %d new messages", account.getDescription(), folderId, System.currentTimeMillis(), newMessages); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folderId, folderName, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Timber.e("Root cause failure in %s:%s was '%s'", account.getDescription(), tLocalFolder.getId(), rootMessage); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folderId, folderName, rootMessage); } } Timber.i("Done synchronizing folder %s:%s", account.getDescription(), folderId); } catch (AuthenticationFailedException e) { handleAuthenticationFailure(account, true); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folderId, folderName, "Authentication failure"); } } catch (Exception e) { Timber.e(e, "synchronizeMailbox"); String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Timber.e(e, "Could not set last checked on folder %s:%s", account.getDescription(), tLocalFolder.getId()); } } for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folderId, folderName, rootMessage); } notifyUserIfCertificateProblem(account, e, true); Timber.e("Failed synchronizing folder %s:%s @ %tc", account.getDescription(), folderId, System.currentTimeMillis()); } finally { if (providedRemoteFolder == null) { closeFolder(remoteFolder); } closeFolder(tLocalFolder); } } @VisibleForTesting MessagingController(Context context, NotificationController notificationController,
Contacts contacts, TransportProvider transportProvider); static synchronized MessagingController getInstance(Context context); void addListener(MessagingListener listener); void refreshListener(MessagingListener listener); void removeListener(MessagingListener listener); Set<MessagingListener> getListeners(); Set<MessagingListener> getListeners(MessagingListener listener); void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener); void listSubFolders(final Account account, final String parentFolderId, final boolean refreshRemote, final MessagingListener listener); void listFoldersSynchronous(final Account account, final boolean refreshRemote,
final MessagingListener listener); void listSubFoldersSynchronous(final Account account, final String parentFolderId, final boolean refreshRemote,
final MessagingListener listener); void searchLocalMessages(final LocalSearch search, final MessagingListener listener); Future<?> searchRemoteMessages(final String acctUuid, final String folderId, final String folderName, final String query,
final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener); void loadSearchResults(final Account account, final String folderName, final List<Message> messages,
final MessagingListener listener); void loadMoreMessages(Account account, String folderId, MessagingListener listener); void synchronizeMailbox(final Account account, final String folderId, final String folderName, final MessagingListener listener,
final Folder providedRemoteFolder); void markAllMessagesRead(final Account account, final String folder); void setFlag(final Account account, final List<Long> messageIds, final Flag flag,
final boolean newState); void setFlagForThreads(final Account account, final List<Long> threadRootIds,
final Flag flag, final boolean newState); void setFlag(Account account, String folderId, List<? extends Message> messages, Flag flag,
boolean newState); void setFlag(Account account, String folderName, String uid, Flag flag,
boolean newState); void clearAllPending(final Account account); void loadMessageRemotePartial(final Account account, final String folderId,
final String uid, final MessagingListener listener); void loadMessageRemote(final Account account, final String folderId,
final String uid, final MessagingListener listener); LocalMessage loadMessage(Account account, String folderId, String uid); void loadAttachment(final Account account, final LocalMessage message, final Part part,
final MessagingListener listener); void sendMessage(final Account account,
final Message message,
MessagingListener listener); void sendPendingMessages(MessagingListener listener); void sendPendingMessages(final Account account,
MessagingListener listener); void getAccountStats(final Context context, final Account account,
final MessagingListener listener); void getSearchAccountStats(final SearchAccount searchAccount,
final MessagingListener listener); AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount,
final MessagingListener listener); void getFolderUnreadMessageCount(final Account account, final String folderId,
final MessagingListener l); boolean isMoveCapable(MessageReference messageReference); boolean isCopyCapable(MessageReference message); boolean isMoveCapable(final Account account); boolean isCopyCapable(final Account account); void moveMessages(final Account srcAccount, final String srcFolder,
List<MessageReference> messageReferences, final String destFolder); void moveMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void moveMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void copyMessages(final Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessagesInThread(Account srcAccount, final String srcFolder,
final List<MessageReference> messageReferences, final String destFolder); void copyMessage(final Account account, final String srcFolder, final MessageReference message,
final String destFolder); void expunge(final Account account, final String folder); void deleteDraft(final Account account, long id); void deleteThreads(final List<MessageReference> messages); void deleteMessage(MessageReference message, final MessagingListener listener); void deleteMessages(List<MessageReference> messages, final MessagingListener listener); @SuppressLint("NewApi") // used for debugging only void debugClearMessagesLocally(final List<MessageReference> messages); void emptyTrash(final Account account, MessagingListener listener); void clearFolder(final Account account, final String folderId, final ActivityListener listener); void sendAlternate(Context context, Account account, LocalMessage message); void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener); void compact(final Account account, final MessagingListener ml); void clear(final Account account, final MessagingListener ml); void recreate(final Account account, final MessagingListener ml); void deleteAccount(Account account); Message saveDraft(final Account account, final Message message, long existingDraftId, boolean saveRemotely); long getId(Message message); MessagingListener getCheckMailListener(); void setCheckMailListener(MessagingListener checkMailListener); Collection<Pusher> getPushers(); boolean setupPushing(final Account account); void stopAllPushing(); void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages,
final boolean flagSyncOnly); void systemStatusChanged(); void cancelNotificationsForAccount(Account account); void cancelNotificationForMessage(Account account, MessageReference messageReference); void clearCertificateErrorNotifications(Account account, CheckDirection direction); void notifyUserIfCertificateProblem(Account account, Exception exception, boolean incoming); static final long INVALID_MESSAGE_ID; } | @Test public void synchronizeMailboxSynchronous_withOneMessageInRemoteFolder_shouldFinishWithoutError() throws Exception { messageCountInRemoteFolder(1); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(listener).synchronizeMailboxFinished(account, FOLDER_ID, FOLDER_NAME, 1, 0); }
@Test public void synchronizeMailboxSynchronous_withEmptyRemoteFolder_shouldFinishWithoutError() throws Exception { messageCountInRemoteFolder(0); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(listener).synchronizeMailboxFinished(account, FOLDER_ID, FOLDER_NAME, 0, 0); }
@Test public void synchronizeMailboxSynchronous_withNegativeMessageCountInRemoteFolder_shouldFinishWithError() throws Exception { messageCountInRemoteFolder(-1); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(listener).synchronizeMailboxFailed(account, FOLDER_ID, FOLDER_NAME, "Exception: Message count -1 for folder FolderID"); }
@Test public void synchronizeMailboxSynchronous_withRemoteFolderProvided_shouldNotOpenRemoteFolder() throws Exception { messageCountInRemoteFolder(1); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, never()).open(Folder.OPEN_MODE_RW); }
@Test public void synchronizeMailboxSynchronous_withNoRemoteFolderProvided_shouldOpenRemoteFolderFromStore() throws Exception { messageCountInRemoteFolder(1); configureRemoteStoreWithFolder(); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, null); verify(remoteFolder).open(Folder.OPEN_MODE_RO); }
@Test public void synchronizeMailboxSynchronous_withRemoteFolderProvided_shouldNotCloseRemoteFolder() throws Exception { messageCountInRemoteFolder(1); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, never()).close(); }
@Test public void synchronizeMailboxSynchronous_withNoRemoteFolderProvided_shouldCloseRemoteFolderFromStore() throws Exception { messageCountInRemoteFolder(1); configureRemoteStoreWithFolder(); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, null); verify(remoteFolder).close(); }
@Test public void synchronizeMailboxSynchronous_withAccountSetToSyncRemoteDeletions_shouldDeleteLocalCopiesOfDeletedMessages() throws Exception { messageCountInRemoteFolder(0); LocalMessage localCopyOfRemoteDeletedMessage = mock(LocalMessage.class); when(account.syncRemoteDeletions()).thenReturn(true); when(localFolder.getAllMessagesAndEffectiveDates()).thenReturn(Collections.singletonMap(MESSAGE_UID1, 0L)); when(localFolder.getMessagesByUids(any(List.class))) .thenReturn(Collections.singletonList(localCopyOfRemoteDeletedMessage)); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(localFolder).destroyMessages(messageListCaptor.capture()); assertEquals(localCopyOfRemoteDeletedMessage, messageListCaptor.getValue().get(0)); }
@Test public void synchronizeMailboxSynchronous_withAccountSetToSyncRemoteDeletions_shouldNotDeleteLocalCopiesOfExistingMessagesAfterEarliestPollDate() throws Exception { messageCountInRemoteFolder(1); Date dateOfEarliestPoll = new Date(); LocalMessage localMessage = localMessageWithCopyOnServer(); when(account.syncRemoteDeletions()).thenReturn(true); when(account.getEarliestPollDate()).thenReturn(dateOfEarliestPoll); when(localMessage.olderThan(dateOfEarliestPoll)).thenReturn(false); when(localFolder.getMessages(null)).thenReturn(Collections.singletonList(localMessage)); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(localFolder, never()).destroyMessages(messageListCaptor.capture()); }
@Test public void synchronizeMailboxSynchronous_withAccountSetToSyncRemoteDeletions_shouldDeleteLocalCopiesOfExistingMessagesBeforeEarliestPollDate() throws Exception { messageCountInRemoteFolder(1); LocalMessage localMessage = localMessageWithCopyOnServer(); Date dateOfEarliestPoll = new Date(); when(account.syncRemoteDeletions()).thenReturn(true); when(account.getEarliestPollDate()).thenReturn(dateOfEarliestPoll); when(localMessage.olderThan(dateOfEarliestPoll)).thenReturn(true); when(localFolder.getAllMessagesAndEffectiveDates()).thenReturn(Collections.singletonMap(MESSAGE_UID1, 0L)); when(localFolder.getMessagesByUids(any(List.class))).thenReturn(Collections.singletonList(localMessage)); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(localFolder).destroyMessages(messageListCaptor.capture()); assertEquals(localMessage, messageListCaptor.getValue().get(0)); }
@Test public void synchronizeMailboxSynchronous_withAccountSetNotToSyncRemoteDeletions_shouldNotDeleteLocalCopiesOfMessages() throws Exception { messageCountInRemoteFolder(0); LocalMessage remoteDeletedMessage = mock(LocalMessage.class); when(account.syncRemoteDeletions()).thenReturn(false); when(localFolder.getMessages(null)).thenReturn(Collections.singletonList(remoteDeletedMessage)); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(localFolder, never()).destroyMessages(messageListCaptor.capture()); }
@Test public void synchronizeMailboxSynchronous_withAccountSupportingFetchingFlags_shouldFetchUnsychronizedMessagesListAndFlags() throws Exception { messageCountInRemoteFolder(1); hasUnsyncedRemoteMessage(); when(remoteFolder.supportsFetchingFlags()).thenReturn(true); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, atLeastOnce()).fetch(any(List.class), fetchProfileCaptor.capture(), any(MessageRetrievalListener.class)); assertTrue(fetchProfileCaptor.getAllValues().get(0).contains(FetchProfile.Item.FLAGS)); assertTrue(fetchProfileCaptor.getAllValues().get(0).contains(FetchProfile.Item.ENVELOPE)); assertEquals(2, fetchProfileCaptor.getAllValues().get(0).size()); }
@Test public void synchronizeMailboxSynchronous_withAccountNotSupportingFetchingFlags_shouldFetchUnsychronizedMessages() throws Exception { messageCountInRemoteFolder(1); hasUnsyncedRemoteMessage(); when(remoteFolder.supportsFetchingFlags()).thenReturn(false); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, atLeastOnce()).fetch(any(List.class), fetchProfileCaptor.capture(), any(MessageRetrievalListener.class)); assertEquals(1, fetchProfileCaptor.getAllValues().get(0).size()); assertTrue(fetchProfileCaptor.getAllValues().get(0).contains(FetchProfile.Item.ENVELOPE)); }
@Test public void synchronizeMailboxSynchronous_withUnsyncedNewSmallMessage_shouldFetchBodyOfSmallMessage() throws Exception { Message smallMessage = buildSmallNewMessage(); messageCountInRemoteFolder(1); hasUnsyncedRemoteMessage(); when(remoteFolder.supportsFetchingFlags()).thenReturn(false); respondToFetchEnvelopesWithMessage(smallMessage); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, atLeast(2)).fetch(any(List.class), fetchProfileCaptor.capture(), any(MessageRetrievalListener.class)); assertEquals(1, fetchProfileCaptor.getAllValues().get(1).size()); assertTrue(fetchProfileCaptor.getAllValues().get(1).contains(FetchProfile.Item.BODY)); }
@Test public void synchronizeMailboxSynchronous_withUnsyncedNewSmallMessage_shouldFetchStructureAndLimitedBodyOfLargeMessage() throws Exception { Message largeMessage = buildLargeNewMessage(); messageCountInRemoteFolder(1); hasUnsyncedRemoteMessage(); when(remoteFolder.supportsFetchingFlags()).thenReturn(false); respondToFetchEnvelopesWithMessage(largeMessage); controller.synchronizeMailboxSynchronous(account, FOLDER_ID, FOLDER_NAME, listener, remoteFolder); verify(remoteFolder, atLeast(4)).fetch(any(List.class), fetchProfileCaptor.capture(), any(MessageRetrievalListener.class)); assertEquals(1, fetchProfileCaptor.getAllValues().get(2).size()); assertEquals(FetchProfile.Item.STRUCTURE, fetchProfileCaptor.getAllValues().get(2).get(0)); assertEquals(1, fetchProfileCaptor.getAllValues().get(3).size()); assertEquals(FetchProfile.Item.BODY_SANE, fetchProfileCaptor.getAllValues().get(3).get(0)); } |
MessageCryptoStructureDetector { 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> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); } | @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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.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 = MessageCryptoStructureDetector.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertNull(cryptoPart); } |
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; } | @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()); } |
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; } | @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); } |
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; } | @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); } |
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; } | @Test public void withShortData__writeTo__shouldWriteData() throws Exception { writeShortTestData(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); deferredFileBody.writeTo(baos); assertArrayEquals(TEST_DATA_SHORT, baos.toByteArray()); } |
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; } | @Test(expected = UnsupportedOperationException.class) public void setEncoding__shouldThrow() throws Exception { deferredFileBody.setEncoding("anything"); } |
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; } | @Test public void getEncoding__shouldReturnEncoding() throws Exception { assertEquals(TEST_ENCODING, deferredFileBody.getEncoding()); } |
StoreSchemaDefinition implements LockableDatabase.SchemaDefinition { @Override public int getVersion() { return LocalStore.DB_VERSION; } StoreSchemaDefinition(LocalStore localStore); @Override int getVersion(); @Override void doDbUpgrade(final SQLiteDatabase db); } | @Test public void getVersion_shouldReturnCurrentDatabaseVersion() { int version = storeSchemaDefinition.getVersion(); assertEquals(LocalStore.DB_VERSION, version); } |
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); } | @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); } |
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); } } } } | @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); } |
MigrationTo60 { @VisibleForTesting static PendingCommand migratePendingCommand(OldPendingCommand oldPendingCommand) { switch (oldPendingCommand.command) { case PENDING_COMMAND_APPEND: { return migrateCommandAppend(oldPendingCommand); } case PENDING_COMMAND_SET_FLAG_BULK: { return migrateCommandSetFlagBulk(oldPendingCommand); } case PENDING_COMMAND_SET_FLAG: { return migrateCommandSetFlag(oldPendingCommand); } case PENDING_COMMAND_MARK_ALL_AS_READ: { return migrateCommandMarkAllAsRead(oldPendingCommand); } case PENDING_COMMAND_MOVE_OR_COPY_BULK: { return migrateCommandMoveOrCopyBulk(oldPendingCommand); } case PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW: { return migrateCommandMoveOrCopyBulkNew(oldPendingCommand); } case PENDING_COMMAND_MOVE_OR_COPY: { return migrateCommandMoveOrCopy(oldPendingCommand); } case PENDING_COMMAND_EMPTY_TRASH: { return migrateCommandEmptyTrash(); } case PENDING_COMMAND_EXPUNGE: { return migrateCommandExpunge(oldPendingCommand); } default: { throw new IllegalArgumentException("Tried to migrate unknown pending command!"); } } } } | @Test public void migrateMoveOrCopy_withUidArray() { OldPendingCommand command = queueMoveOrCopy(SOURCE_FOLDER, DEST_FOLDER, IS_COPY, UID_ARRAY); PendingMoveOrCopy pendingCommand = (PendingMoveOrCopy) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.srcFolder); assertEquals(DEST_FOLDER, pendingCommand.destFolder); assertEquals(IS_COPY, pendingCommand.isCopy); assertEquals(asList(UID_ARRAY), pendingCommand.uids); assertNull(pendingCommand.newUidMap); }
@Test public void migrateMoveOrCopy_withUidMap() { OldPendingCommand command = queueMoveOrCopy(SOURCE_FOLDER, DEST_FOLDER, IS_COPY, UID_MAP); PendingMoveOrCopy pendingCommand = (PendingMoveOrCopy) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.srcFolder); assertEquals(DEST_FOLDER, pendingCommand.destFolder); assertEquals(IS_COPY, pendingCommand.isCopy); assertEquals(UID_MAP, pendingCommand.newUidMap); assertNull(pendingCommand.uids); }
@Test public void migrateMoveOrCopy_withOldFormat() { OldPendingCommand command = queueMoveOrCopyOld(SOURCE_FOLDER, DEST_FOLDER, IS_COPY, UID_ARRAY); PendingMoveOrCopy pendingCommand = (PendingMoveOrCopy) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.srcFolder); assertEquals(DEST_FOLDER, pendingCommand.destFolder); assertEquals(IS_COPY, pendingCommand.isCopy); assertEquals(asList(UID_ARRAY), pendingCommand.uids); assertNull(pendingCommand.newUidMap); }
@Test public void migrateMoveOrCopy__withEvenOlderFormat() { OldPendingCommand command = queueMoveOrCopyEvenOlder(SOURCE_FOLDER, DEST_FOLDER, UID, IS_COPY); PendingMoveOrCopy pendingCommand = (PendingMoveOrCopy) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.srcFolder); assertEquals(DEST_FOLDER, pendingCommand.destFolder); assertEquals(IS_COPY, pendingCommand.isCopy); assertEquals(Collections.singletonList(UID), pendingCommand.uids); assertNull(pendingCommand.newUidMap); }
@Test public void migrateSetFlag() { OldPendingCommand command = queueSetFlagBulk(SOURCE_FOLDER, FLAG_STATE, FLAG, UID_ARRAY); PendingSetFlag pendingCommand = (PendingSetFlag) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.folder); assertEquals(FLAG_STATE, pendingCommand.newState); assertEquals(FLAG, pendingCommand.flag); assertEquals(asList(UID_ARRAY), pendingCommand.uids); }
@Test public void migrateSetFlag_oldFormat() { OldPendingCommand command = queueSetFlagOld(SOURCE_FOLDER, FLAG_STATE, FLAG, UID); PendingSetFlag pendingCommand = (PendingSetFlag) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.folder); assertEquals(FLAG_STATE, pendingCommand.newState); assertEquals(FLAG, pendingCommand.flag); assertEquals(Collections.singletonList(UID), pendingCommand.uids); }
@Test public void migrateExpunge() { OldPendingCommand command = queueExpunge(SOURCE_FOLDER); PendingExpunge pendingCommand = (PendingExpunge) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.folder); }
@Test public void migrateEmptyTrash() { OldPendingCommand command = queueEmptyTrash(); PendingCommand pendingCommand = MigrationTo60.migratePendingCommand(command); assertTrue(pendingCommand instanceof PendingEmptyTrash); }
@Test public void migrateMarkAllMessagesRead() { OldPendingCommand command = queueMarkAllMessagesRead(SOURCE_FOLDER); PendingMarkAllAsRead pendingCommand = (PendingMarkAllAsRead) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.folder); }
@Test public void migrateAppend() { OldPendingCommand command = queueAppend(SOURCE_FOLDER, UID); PendingAppend pendingCommand = (PendingAppend) MigrationTo60.migratePendingCommand(command); assertEquals(SOURCE_FOLDER, pendingCommand.folder); assertEquals(UID, pendingCommand.uid); } |
MessageViewInfoExtractor { @VisibleForTesting ViewableExtractedText extractTextFromViewables(List<Viewable> viewables) throws MessagingException { try { boolean hideDivider = true; StringBuilder text = new StringBuilder(); StringBuilder html = new StringBuilder(); for (Viewable viewable : viewables) { if (viewable instanceof Textual) { text.append(buildText(viewable, !hideDivider)); html.append(buildHtml(viewable, !hideDivider)); hideDivider = false; } else if (viewable instanceof MessageHeader) { MessageHeader header = (MessageHeader) viewable; Part containerPart = header.getContainerPart(); Message innerMessage = header.getMessage(); addTextDivider(text, containerPart, !hideDivider); addMessageHeaderText(text, innerMessage); addHtmlDivider(html, containerPart, !hideDivider); addMessageHeaderHtml(html, innerMessage); hideDivider = true; } else if (viewable instanceof Alternative) { Alternative alternative = (Alternative) viewable; List<Viewable> textAlternative = alternative.getText().isEmpty() ? alternative.getHtml() : alternative.getText(); List<Viewable> htmlAlternative = alternative.getHtml().isEmpty() ? alternative.getText() : alternative.getHtml(); boolean divider = !hideDivider; for (Viewable textViewable : textAlternative) { text.append(buildText(textViewable, divider)); divider = true; } divider = !hideDivider; for (Viewable htmlViewable : htmlAlternative) { html.append(buildHtml(htmlViewable, divider)); divider = true; } hideDivider = false; } } String sanitizedHtml = htmlProcessor.processForDisplay(html.toString()); return new ViewableExtractedText(text.toString(), sanitizedHtml); } catch (Exception e) { throw new MessagingException("Couldn't extract viewable parts", e); } } @VisibleForTesting MessageViewInfoExtractor(Context context, AttachmentInfoExtractor attachmentInfoExtractor,
ICalendarInfoExtractor iCalendarInfoExtractor, HtmlProcessor htmlProcessor); static MessageViewInfoExtractor getInstance(); @WorkerThread MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations cryptoAnnotations); } | @Test public void testShouldSanitizeOutputHtml() throws MessagingException { TextBody body = new TextBody(BODY_TEXT); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, body); message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain; format=flowed"); HtmlProcessor htmlProcessor = mock(HtmlProcessor.class); MessageViewInfoExtractor messageViewInfoExtractor = new MessageViewInfoExtractor(context, null, null, htmlProcessor); String value = "--sanitized html--"; when(htmlProcessor.processForDisplay(anyString())).thenReturn(value); List<Part> outputNonViewableParts = new ArrayList<>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, null); ViewableExtractedText viewableExtractedText = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); assertSame(value, viewableExtractedText.html); }
@Test public void testSimplePlainTextMessage() throws MessagingException { TextBody body = new TextBody(BODY_TEXT); MimeMessage message = new MimeMessage(); message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); MimeMessageHelper.setBody(message, body); List<Part> outputNonViewableParts = new ArrayList<>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, null); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = BODY_TEXT; String expectedHtml = "<pre class=\"k9mail\">" + "K-9 Mail rocks :>" + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }
@Test public void testTextPlainFormatFlowed() throws MessagingException { TextBody body = new TextBody(BODY_TEXT_FLOWED); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, body); message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain; format=flowed"); List<Part> outputNonViewableParts = new ArrayList<>(); List<ICalPart> outputCalendarParts = new ArrayList<>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, outputCalendarParts); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = "K-9 Mail rocks :> flowed line\r\n" + "not flowed line"; String expectedHtml = "<pre class=\"k9mail\">" + "K-9 Mail rocks :> flowed line<br />not flowed line" + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }
@Test public void testSimpleHtmlMessage() throws MessagingException { String bodyText = "<strong>K-9 Mail</strong> rocks :>"; TextBody body = new TextBody(bodyText); MimeMessage message = new MimeMessage(); message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/html"); MimeMessageHelper.setBody(message, body); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, null, null); assertEquals(outputViewableParts.size(), 1); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = BODY_TEXT; String expectedHtml = bodyText; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }
@Test public void testMultipartPlainTextMessage() throws MessagingException { String bodyText1 = "text body 1"; String bodyText2 = "text body 2"; TextBody body1 = new TextBody(bodyText1); TextBody body2 = new TextBody(bodyText2); MimeMultipart multipart = MimeMultipart.newInstance(); MimeBodyPart bodyPart1 = new MimeBodyPart(body1, "text/plain"); MimeBodyPart bodyPart2 = new MimeBodyPart(body2, "text/plain"); multipart.addBodyPart(bodyPart1); multipart.addBodyPart(bodyPart2); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, multipart); List<Part> outputNonViewableParts = new ArrayList<>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, null); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = bodyText1 + "\r\n\r\n" + "------------------------------------------------------------------------\r\n\r\n" + bodyText2; String expectedHtml = "<pre class=\"k9mail\">" + bodyText1 + "</pre>" + "<p style=\"margin-top: 2.5em; margin-bottom: 1em; " + "border-bottom: 1px solid #000\"></p>" + "<pre class=\"k9mail\">" + bodyText2 + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }
@Test public void testTextPlusRfc822Message() throws MessagingException { K9ActivityCommon.setLanguage(context, "en"); Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("GMT+01:00")); String innerBodyText = "Hey there. I'm inside a message/rfc822 (inline) attachment."; TextBody textBody = new TextBody(BODY_TEXT); TextBody innerBody = new TextBody(innerBodyText); MimeMessage innerMessage = new MimeMessage(); innerMessage.addSentDate(new Date(112, 2, 17), false); innerMessage.setRecipients(RecipientType.TO, new Address[] { new Address("[email protected]") }); innerMessage.setSubject("Subject"); innerMessage.setFrom(new Address("[email protected]")); MimeMessageHelper.setBody(innerMessage, innerBody); MimeMultipart multipart = MimeMultipart.newInstance(); MimeBodyPart bodyPart1 = new MimeBodyPart(textBody, "text/plain"); MimeBodyPart bodyPart2 = new MimeBodyPart(innerMessage, "message/rfc822"); bodyPart2.setHeader("Content-Disposition", "inline; filename=\"message.eml\""); multipart.addBodyPart(bodyPart1); multipart.addBodyPart(bodyPart2); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, multipart); List<Part> outputNonViewableParts = new ArrayList<Part>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, null); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = BODY_TEXT + "\r\n\r\n" + "----- message.eml ------------------------------------------------------" + "\r\n\r\n" + "From: [email protected]" + "\r\n" + "To: [email protected]" + "\r\n" + "Sent: Sat Mar 17 00:00:00 GMT+01:00 2012" + "\r\n" + "Subject: Subject" + "\r\n" + "\r\n" + innerBodyText; String expectedHtml = "<pre class=\"k9mail\">" + BODY_TEXT_HTML + "</pre>" + "<p style=\"margin-top: 2.5em; margin-bottom: 1em; border-bottom: " + "1px solid #000\">message.eml</p>" + "<table style=\"border: 0\">" + "<tr>" + "<th style=\"text-align: left; vertical-align: top;\">From:</th>" + "<td>[email protected]</td>" + "</tr><tr>" + "<th style=\"text-align: left; vertical-align: top;\">To:</th>" + "<td>[email protected]</td>" + "</tr><tr>" + "<th style=\"text-align: left; vertical-align: top;\">Sent:</th>" + "<td>Sat Mar 17 00:00:00 GMT+01:00 2012</td>" + "</tr><tr>" + "<th style=\"text-align: left; vertical-align: top;\">Subject:</th>" + "<td>Subject</td>" + "</tr>" + "</table>" + "<pre class=\"k9mail\">" + innerBodyText + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }
@Test public void testMultipartDigestWithMessages() throws Exception { String data = "Content-Type: multipart/digest; boundary=\"bndry\"\r\n" + "\r\n" + "--bndry\r\n" + "\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "text body of first message\r\n" + "\r\n" + "--bndry\r\n" + "\r\n" + "Subject: subject of second message\r\n" + "Content-Type: multipart/alternative; boundary=\"bndry2\"\r\n" + "\r\n" + "--bndry2\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "text part of second message\r\n" + "\r\n" + "--bndry2\r\n" + "Content-Type: text/html\"\r\n" + "\r\n" + "html part of second message\r\n" + "\r\n" + "--bndry2--\r\n" + "\r\n" + "--bndry--\r\n"; MimeMessage message = MimeMessage.parseMimeMessage(new ByteArrayInputStream(data.getBytes()), false); List<Part> outputNonViewableParts = new ArrayList<>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); List<ICalPart> outputCalendarParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts, outputCalendarParts); String expectedExtractedText = "Subject: (No subject)\r\n" + "\r\n" + "text body of first message\r\n" + "\r\n" + "\r\n" + "------------------------------------------------------------------------\r\n" + "\r\n" + "Subject: subject of second message\r\n" + "\r\n" + "text part of second message\r\n"; String expectedHtmlText = "<table style=\"border: 0\">" + "<tr><th style=\"text-align: left; vertical-align: top;\">Subject:</th><td>(No subject)</td></tr>" + "</table>" + "<pre class=\"k9mail\">text body of first message<br /></pre>" + "<p style=\"margin-top: 2.5em; margin-bottom: 1em; border-bottom: 1px solid #000\"></p>" + "<table style=\"border: 0\">" + "<tr><th style=\"text-align: left; vertical-align: top;\">Subject:</th><td>subject of second message</td></tr>" + "</table>" + "<pre class=\"k9mail\">text part of second message<br /></pre>"; assertEquals(4, outputViewableParts.size()); assertEquals("subject of second message", ((MessageHeader) outputViewableParts.get(2)).getMessage().getSubject()); ViewableExtractedText firstMessageExtractedText = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); assertEquals(expectedExtractedText, firstMessageExtractedText.text); assertEquals(expectedHtmlText, firstMessageExtractedText.html); } |
MessageViewInfoExtractor { @WorkerThread public MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations cryptoAnnotations) throws MessagingException { ArrayList<Part> extraParts = new ArrayList<>(); Part cryptoContentPart = MessageCryptoStructureDetector.findPrimaryEncryptedOrSignedPart(message, extraParts); if (cryptoContentPart == null) { if (cryptoAnnotations != null && !cryptoAnnotations.isEmpty()) { Timber.e("Got crypto message cryptoContentAnnotations but no crypto root part!"); } return extractSimpleMessageForView(message, message); } boolean isOpenPgpEncrypted = (MessageCryptoStructureDetector.isPartMultipartEncrypted(cryptoContentPart) && MessageCryptoStructureDetector.isMultipartEncryptedOpenPgpProtocol(cryptoContentPart)) || MessageCryptoStructureDetector.isPartPgpInlineEncrypted(cryptoContentPart); boolean isSMimeEncrypted = (MessageCryptoStructureDetector.isPartMultipartEncrypted(cryptoContentPart) && MessageCryptoStructureDetector.isMultipartEncryptedSMimeProtocol(cryptoContentPart)); if ((!QMail.isOpenPgpProviderConfigured() && isOpenPgpEncrypted) || (!QMail.isSMimeProviderConfigured() && isSMimeEncrypted)) { CryptoResultAnnotation noProviderAnnotation = CryptoResultAnnotation.createErrorAnnotation( CryptoError.SMIME_ENCRYPTED_NO_PROVIDER, null); return MessageViewInfo.createWithErrorState(message, false) .withCryptoData(noProviderAnnotation, null, null, null); } CryptoResultAnnotation cryptoContentPartAnnotation = cryptoAnnotations != null ? cryptoAnnotations.get(cryptoContentPart) : null; if (cryptoContentPartAnnotation != null) { return extractCryptoMessageForView(message, extraParts, cryptoContentPart, cryptoContentPartAnnotation); } return extractSimpleMessageForView(message, message); } @VisibleForTesting MessageViewInfoExtractor(Context context, AttachmentInfoExtractor attachmentInfoExtractor,
ICalendarInfoExtractor iCalendarInfoExtractor, HtmlProcessor htmlProcessor); static MessageViewInfoExtractor getInstance(); @WorkerThread MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations cryptoAnnotations); } | @Test public void extractMessage_withAttachment() throws Exception { BodyPart attachmentPart = bodypart("application/octet-stream"); Message message = messageFromBody(multipart("mixed", bodypart("text/plain", "text"), attachmentPart )); AttachmentViewInfo attachmentViewInfo = mock(AttachmentViewInfo.class); setupAttachmentInfoForPart(attachmentPart, attachmentViewInfo); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertSame(attachmentViewInfo, messageViewInfo.attachments.get(0)); assertNull(messageViewInfo.cryptoResultAnnotation); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
@Test public void extractMessage_withCryptoAnnotation() throws Exception { Message message = messageFromBody(multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain", "text"), bodypart("application/pgp-signature") )); CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation( null, null, null, null, null, false); MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(message, annotation); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
@Test public void extractMessage_withCryptoAnnotation_andReplacementPart() throws Exception { Message message = messageFromBody(multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain", "text"), bodypart("application/pgp-signature") )); MimeBodyPart replacementPart = bodypart("text/plain", "replacement text"); CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation( null, null, null, null, replacementPart, false); MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(message, annotation); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations); assertEquals("<pre class=\"k9mail\">replacement text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
@Test public void extractMessage_withCryptoAnnotation_andExtraText() throws Exception { MimeBodyPart signedPart = multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain", "text"), bodypart("application/pgp-signature") ); BodyPart extraText = bodypart("text/plain", "extra text"); Message message = messageFromBody(multipart("mixed", signedPart, extraText )); CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation( null, null, null, null, null, false); MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(signedPart, annotation); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); assertEquals("extra text", messageViewInfo.extraText); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
@Test public void extractMessage_withCryptoAnnotation_andExtraAttachment() throws Exception { MimeBodyPart signedPart = multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain", "text"), bodypart("application/pgp-signature") ); BodyPart extraAttachment = bodypart("application/octet-stream"); Message message = messageFromBody(multipart("mixed", signedPart, extraAttachment )); CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation( null, null, null, null, null, false); MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(signedPart, annotation); AttachmentViewInfo attachmentViewInfo = mock(AttachmentViewInfo.class); setupAttachmentInfoForPart(extraAttachment, attachmentViewInfo); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertSame(annotation, messageViewInfo.cryptoResultAnnotation); assertSame(attachmentViewInfo, messageViewInfo.extraAttachments.get(0)); assertTrue(messageViewInfo.attachments.isEmpty()); }
@Test public void extractMessage_openPgpEncrypted_withoutAnnotations() throws Exception { Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null); assertEquals(CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER, messageViewInfo.cryptoResultAnnotation.getErrorType()); assertNull(messageViewInfo.text); assertNull(messageViewInfo.attachments); assertNull(messageViewInfo.extraAttachments); }
@Test public void extractMessage_multipartSigned_UnknownProtocol() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pkcs7-signature\"", bodypart("text/plain", "text"), bodypart("application/pkcs7-signature", "signature") ) ); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertNull(messageViewInfo.cryptoResultAnnotation); assertTrue(messageViewInfo.attachments.isEmpty()); assertTrue(messageViewInfo.extraAttachments.isEmpty()); }
@Test public void extractMessage_multipartSigned_UnknownProtocol_withExtraAttachments() throws Exception { BodyPart extraAttachment = bodypart("application/octet-stream"); Message message = messageFromBody( multipart("mixed", multipart("signed", "protocol=\"application/pkcs7-signature\"", bodypart("text/plain", "text"), bodypart("application/pkcs7-signature", "signature") ), extraAttachment ) ); AttachmentViewInfo mock = mock(AttachmentViewInfo.class); setupAttachmentInfoForPart(extraAttachment, mock); MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null); assertEquals("<pre class=\"k9mail\">text</pre>", messageViewInfo.text); assertNull(messageViewInfo.cryptoResultAnnotation); assertSame(mock, messageViewInfo.attachments.get(0)); assertTrue(messageViewInfo.extraAttachments.isEmpty()); } |
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); } | @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")); } |
LocalStore extends Store { static Part findPartById(Part searchRoot, long partId) { if (searchRoot instanceof LocalMessage) { LocalMessage localMessage = (LocalMessage) searchRoot; if (localMessage.getMessagePartId() == partId) { return localMessage; } } Stack<Part> partStack = new Stack<>(); partStack.add(searchRoot); while (!partStack.empty()) { Part part = partStack.pop(); if (part instanceof LocalPart) { LocalPart localBodyPart = (LocalPart) part; if (localBodyPart.getPartId() == partId) { return part; } } Body body = part.getBody(); if (body instanceof Multipart) { Multipart innerMultipart = (Multipart) body; for (BodyPart innerPart : innerMultipart.getBodyParts()) { partStack.add(innerPart); } } if (body instanceof Part) { partStack.add((Part) body); } } return null; } private LocalStore(final Account account, final Context context); static LocalStore getInstance(Account account, Context context); static void removeAccount(Account account); void switchLocalStorage(final String newStorageProviderId); long getSize(); void compact(); void clear(); @Override @NonNull LocalFolder getFolder(String remoteId); @Override @NonNull List<LocalFolder> getFolders(boolean forceListAll); @Override @NonNull List<LocalFolder> getSubFolders(final String parentFolderId, boolean forceListAll); @Override void checkSettings(); void delete(); void recreate(); void resetVisibleLimits(int visibleLimit); List<PendingCommand> getPendingCommands(); void addPendingCommand(PendingCommand command); void removePendingCommand(final PendingCommand command); void removePendingCommands(); @Override boolean isMoveCapable(); @Override boolean isCopyCapable(); List<LocalMessage> searchForMessages(MessageRetrievalListener<LocalMessage> retrievalListener,
LocalSearch search); List<LocalMessage> getMessagesInThread(final long rootId); AttachmentInfo getAttachmentInfo(final String attachmentId); @Nullable OpenPgpDataSource getAttachmentDataSource(final String partId); File getAttachmentFile(String attachmentId); void createFolders(final List<LocalFolder> foldersToCreate, final int visibleLimit); LockableDatabase getDatabase(); MessageFulltextCreator getMessageFulltextCreator(); void setFlag(final List<Long> messageIds, final Flag flag, final boolean newState); void setFlagForThreads(final List<Long> threadRootIds, Flag flag, final boolean newState); Map<String, List<String>> getFoldersAndUids(final List<Long> messageIds,
final boolean threadedList); static String getColumnNameForFlag(Flag flag); static final int DB_VERSION; } | @Test public void findPartById__withRootLocalBodyPart() throws Exception { LocalBodyPart searchRoot = new LocalBodyPart(null, null, 123L, -1L); Part part = LocalStore.findPartById(searchRoot, 123L); assertSame(searchRoot, part); }
@Test public void findPartById__withRootLocalMessage() throws Exception { LocalMessage searchRoot = new LocalMessage(null, "uid", null); searchRoot.setMessagePartId(123L); Part part = LocalStore.findPartById(searchRoot, 123L); assertSame(searchRoot, part); }
@Test public void findPartById__withNestedLocalBodyPart() throws Exception { LocalBodyPart searchRoot = new LocalBodyPart(null, null, 1L, -1L); LocalBodyPart needlePart = new LocalBodyPart(null, null, 123L, -1L); MimeMultipart mimeMultipart = new MimeMultipart("boundary"); mimeMultipart.addBodyPart(needlePart); searchRoot.setBody(mimeMultipart); Part part = LocalStore.findPartById(searchRoot, 123L); assertSame(needlePart, part); }
@Test public void findPartById__withNestedLocalMessagePart() throws Exception { LocalBodyPart searchRoot = new LocalBodyPart(null, null, 1L, -1L); LocalMimeMessage needlePart = new LocalMimeMessage(null, null, 123L); MimeMultipart mimeMultipart = new MimeMultipart("boundary"); mimeMultipart.addBodyPart(new MimeBodyPart(needlePart)); searchRoot.setBody(mimeMultipart); Part part = LocalStore.findPartById(searchRoot, 123L); assertSame(needlePart, part); }
@Test public void findPartById__withTwoTimesNestedLocalMessagePart() throws Exception { LocalBodyPart searchRoot = new LocalBodyPart(null, null, 1L, -1L); LocalMimeMessage needlePart = new LocalMimeMessage(null, null, 123L); MimeMultipart mimeMultipartInner = new MimeMultipart("boundary"); mimeMultipartInner.addBodyPart(new MimeBodyPart(needlePart)); MimeMultipart mimeMultipart = new MimeMultipart("boundary"); mimeMultipart.addBodyPart(new MimeBodyPart(mimeMultipartInner)); searchRoot.setBody(mimeMultipart); Part part = LocalStore.findPartById(searchRoot, 123L); assertSame(needlePart, part); } |
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(); } | @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); } |
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(); } | @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")); } |
MessageCryptoHelper { public void asyncStartOrResumeProcessingMessage(Message message, MessageCryptoCallback callback, OpenPgpDecryptionResult cachedOpenPgpDecryptionResult, SMimeDecryptionResult cachedSMimeDecryptionResult, boolean processSignedOnly) { if (this.currentMessage != null) { reattachCallback(message, callback); return; } this.messageAnnotations = new MessageCryptoAnnotations(); this.state = State.START; this.currentMessage = message; this.cachedOpenPgpDecryptionResult = cachedOpenPgpDecryptionResult; this.cachedSMimeDecryptionResult = cachedSMimeDecryptionResult; this.callback = callback; this.processSignedOnly = processSignedOnly; nextStep(); } MessageCryptoHelper(Context context, OpenPgpApiFactory openPgpApiFactory, SMimeApiFactory sMimeApiFactory,
AutocryptOperations autocryptOperations); boolean isConfiguredForOutdatedCryptoProvider(); boolean isConfiguredForOutdatedOpenPgpProvider(); boolean isConfiguredForOutdatedSMimeProvider(); void asyncStartOrResumeProcessingMessage(Message message, MessageCryptoCallback callback,
OpenPgpDecryptionResult cachedOpenPgpDecryptionResult, SMimeDecryptionResult cachedSMimeDecryptionResult, boolean processSignedOnly); void cancelIfRunning(); void onActivityResult(int requestCode, int resultCode, Intent data); void detachCallback(); } | @Test public void textPlain_withOpenPgpApi_checksForAutocryptHeader() throws Exception { setUpWithOpenPgpApi(); MimeMessage message = new MimeMessage(); message.setUid("msguid"); message.setHeader("Content-Type", "text/plain"); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); MessageCryptoAnnotations annotations = captor.getValue(); assertTrue(annotations.isEmpty()); verifyNoMoreInteractions(messageCryptoCallback); verify(autocryptOperations).hasAutocryptHeader(message); verifyNoMoreInteractions(autocryptOperations); }
@Test public void textPlainWithAutocrypt_withOpenPgpApi() throws Exception { setUpWithOpenPgpApi(); MimeMessage message = new MimeMessage(); message.setUid("msguid"); message.setHeader("Content-Type", "text/plain"); when(autocryptOperations.hasAutocryptHeader(message)).thenReturn(true); when(autocryptOperations.addAutocryptPeerUpdateToIntentIfPresent(same(message), any(Intent.class))).thenReturn(true); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); MessageCryptoAnnotations annotations = captor.getValue(); assertTrue(annotations.isEmpty()); verifyNoMoreInteractions(messageCryptoCallback); ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(autocryptOperations).addAutocryptPeerUpdateToIntentIfPresent(same(message), intentCaptor.capture()); verify(openPgpApi).executeApiAsync(same(intentCaptor.getValue()), same((InputStream) null), same((OutputStream) null), any(IOpenPgpCallback.class)); }
@Test public void multipartSignedOpenPgp__withNullBody_withOpenPgpApi__shouldReturnSignedIncomplete() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain"), bodypart("application/pgp-signature") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, true); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.OPENPGP_SIGNED_BUT_INCOMPLETE, null, null, null, null, null, null, null); }
@Test public void multipartEncryptedOpenPgp__withNullBody_withOpenPgpApi__shouldReturnEncryptedIncomplete() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertPartAnnotationHasState( message, messageCryptoCallback, CryptoError.OPENPGP_ENCRYPTED_BUT_INCOMPLETE, null, null, null, null, null, null, null); }
@Test public void multipartEncrypted__withUnknownProtocol_withOpenPgpApi__shouldReturnEncryptedUnsupported() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("encrypted", "protocol=\"application/bad-protocol\"", bodypart("application/bad-protocol", "content"), bodypart("application/octet-stream", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.ENCRYPTED_BUT_UNSUPPORTED, null, null, null, null, null, null, null); }
@Test public void multipartSigned__withUnknownProtocol_withOpenPgpApi__shouldReturnSignedUnsupported() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/bad-protocol\"", bodypart("text/plain", "content"), bodypart("application/bad-protocol", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, true); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.SIGNED_BUT_UNSUPPORTED, null, null, null, null, null, null, null); }
@Test public void multipartSignedOpenPgp_withOpenPgpApi__withSignOnlyDisabled__shouldReturnNothing() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain", "content"), bodypart("application/pgp-signature", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); }
@Test public void multipartSignedOpenPgp_withOpenPgpApi__withSignOnlyDisabledAndNullBody__shouldReturnNothing() throws Exception { setUpWithOpenPgpApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain"), bodypart("application/pgp-signature") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); }
@Test public void textPlain_withSMimeApi() throws Exception { setUpWithSMimeApi(); MimeMessage message = new MimeMessage(); message.setUid("msguid"); message.setHeader("Content-Type", "text/plain"); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); MessageCryptoAnnotations annotations = captor.getValue(); assertTrue(annotations.isEmpty()); verifyNoMoreInteractions(messageCryptoCallback); }
@Test public void multipartEncryptedUnknownProtocol_withSMimeApi__shouldReturnEncryptedUnsupported() throws Exception { setUpWithSMimeApi(); Message message = messageFromBody( multipart("encrypted", "protocol=\"application/bad-protocol\"", bodypart("application/bad-protocol", "content"), bodypart("application/octet-stream", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.ENCRYPTED_BUT_UNSUPPORTED, null, null, null, null, null, null, null); }
@Test public void multipartSignedUnknownProtocol_withSMimeApi__shouldReturnSignedUnsupported() throws Exception { setUpWithSMimeApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/bad-protocol\"", bodypart("text/plain", "content"), bodypart("application/bad-protocol", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, true); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.SIGNED_BUT_UNSUPPORTED, null, null, null, null, null, null, null); }
@Test public void multipartSignedUnknownProtocol_withSMimeApi_withSignOnlyDisabled__shouldReturnNothing() throws Exception { setUpWithSMimeApi(); Message message = messageFromBody( multipart("signed", "protocol=\"application/bad-protocol\"", bodypart("text/plain", "content"), bodypart("application/bad-protocol", "content") ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); }
@Test public void multipartEncryptedSMime_withOpenPgpApi__shouldReturnEncryptedNoProvider() throws Exception { setUpWithOpenPgpApi(); Body encryptedBody = spy(new TextBody("encrypted data")); Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pkcs7-mime\"", bodypart("application/pkcs7-mime", "content"), bodypart("application/octet-stream", encryptedBody) ) ); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.SMIME_ENCRYPTED_NO_PROVIDER, null, null, null, null, null, null, null); }
@Test public void multipartSignedSMime_withOpenPgpApi_withSignOnlyDisabled__shouldReturnNothing() throws Exception { setUpWithOpenPgpApi(); BodyPart signedBodyPart = spy(bodypart("text/plain", "content")); Message message = messageFromBody( multipart("signed", "protocol=\"application/pkcs7-signature\"", signedBodyPart, bodypart("application/pkcs7-signature", "content") ) ); message.setFrom(Address.parse("Test <[email protected]>")[0]); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); }
@Test public void multipartSignedSMime_withOpenPgpApi_withSignOnly__shouldReturnSignedNoProvider() throws Exception { setUpWithOpenPgpApi(); BodyPart signedBodyPart = spy(bodypart("text/plain", "content")); Message message = messageFromBody( multipart("signed", "protocol=\"application/pkcs7-signature\"", signedBodyPart, bodypart("application/pkcs7-signature", "content") ) ); message.setFrom(Address.parse("Test <[email protected]>")[0]); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, true); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.SMIME_SIGNED_NO_PROVIDER, null, null, null, null, null, null, null); }
@Test public void multipartEncryptedOpenPgp_withSMimeApi__shouldReturnEncryptedNoProvider() throws Exception { setUpWithSMimeApi(); Body encryptedBody = spy(new TextBody("encrypted data")); Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted", "content"), bodypart("application/octet-stream", encryptedBody) ) ); message.setFrom(Address.parse("Test <[email protected]>")[0]); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER, null, null, null, null, null, null, null); }
@Test public void multipartSignedOpenPgp_withSMimeApi_withSignOnlyDisabled__shouldReturnNothing() throws Exception { setUpWithSMimeApi(); BodyPart signedBodyPart = spy(bodypart("text/plain", "content")); Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", signedBodyPart, bodypart("application/pgp-signature", "content") ) ); message.setFrom(Address.parse("Test <[email protected]>")[0]); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, false); assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); }
@Test public void multipartSignedOpenPgp_withSMimeApi_withSignOnlyEnabled__shouldReturnSignedNoProvider() throws Exception { setUpWithSMimeApi(); BodyPart signedBodyPart = spy(bodypart("text/plain", "content")); Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", signedBodyPart, bodypart("application/pgp-signature", "content") ) ); message.setFrom(Address.parse("Test <[email protected]>")[0]); MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, null, true); assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.OPENPGP_SIGNED_NO_PROVIDER, null, null, null, null, null, null, null); } |
MessageCryptoStructureDetector { public static List<Part> findMultipartEncryptedParts(Part startPart) { List<Part> encryptedParts = new ArrayList<>(); Stack<Part> partsToCheck = new Stack<>(); partsToCheck.push(startPart); while (!partsToCheck.isEmpty()) { Part part = partsToCheck.pop(); Body body = part.getBody(); if (isPartMultipartEncrypted(part)) { encryptedParts.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 encryptedParts; } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); } | @Test public void findEncryptedPartsShouldReturnEmptyListForEmptyMessage() throws Exception { MimeMessage emptyMessage = new MimeMessage(); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(emptyMessage); assertEquals(0, encryptedParts.size()); }
@Test public void findEncryptedPartsShouldReturnEmptyListForSimpleMessage() throws Exception { MimeMessage message = new MimeMessage(); message.setBody(new TextBody("message text")); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(0, encryptedParts.size()); }
@Test public void findEncrypted__withMultipartEncrypted__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(message, encryptedParts.get(0)); }
@Test public void findEncrypted__withBadProtocol__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("encrypted", "protocol=\"application/not-pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream", "content") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertTrue(encryptedParts.isEmpty()); }
@Test public void findEncrypted__withBadProtocolAndNoBody__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(message, encryptedParts.get(0)); }
@Test public void findEncrypted__withEmptyProtocol__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("encrypted", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream", "content") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertTrue(encryptedParts.isEmpty()); }
@Test public void findEncrypted__withMissingEncryptedBody__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertTrue(encryptedParts.isEmpty()); }
@Test public void findEncrypted__withBadStructure__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/octet-stream") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertTrue(encryptedParts.isEmpty()); }
@Test public void findEncrypted__withMultipartMixedSubEncrypted__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubEncryptedAndEncrypted__shouldReturnBoth() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ), multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(2, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); assertSame(getPart(message, 1), encryptedParts.get(1)); }
@Test public void findEncrypted__withMultipartMixedSubTextAndEncrypted__shouldReturnEncrypted() throws Exception { Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ) ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 1), encryptedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubEncryptedAndText__shouldReturnEncrypted() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("encrypted", "protocol=\"application/pgp-encrypted\"", bodypart("application/pgp-encrypted"), bodypart("application/octet-stream") ), bodypart("text/plain") ) ); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(message); assertEquals(1, encryptedParts.size()); assertSame(getPart(message, 0), encryptedParts.get(0)); } |
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; } | @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); } |
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; } | @Test public void getValueForUnknownMessage_returnsNull() { String result = cache.getValueForMessage(1L, "subject"); assertNull(result); } |
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; } | @Test public void getValueForUnknownThread_returnsNull() { String result = cache.getValueForThread(1L, "subject"); assertNull(result); } |
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; } | @Test public void isMessageHidden_returnsFalseForUnknownMessage() { boolean result = cache.isMessageHidden(localMessageId, localMessageFolderId); assertFalse(result); } |
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); } | @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]")); } |
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); } | @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); } |
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); } | @Test public void cancel_shouldCallCancelOnAlarmManager() throws Exception { configureDozeSupport(true); addAppToBatteryOptimizationWhitelist(); alarmManager.cancel(PENDING_INTENT); verify(systemAlarmManager).cancel(PENDING_INTENT); } |
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); } | @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); } |
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(); } | @SuppressWarnings("ConstantConditions") @Test public void testIsMailTo_nullArgument() { Uri uri = null; boolean result = MailTo.isMailTo(uri); assertFalse(result); } |
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(); } | @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)); } |
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(); } | @Test public void testGetSubject() { Uri uri = Uri.parse("mailto:?subject=Hello"); MailTo mailToHelper = MailTo.parse(uri); String subject = mailToHelper.getSubject(); assertEquals(subject, "Hello"); } |
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(); } | @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"); } |
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); } | @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); } |
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); } | @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()); } |
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); } | @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); } |
ReplyToParser { public ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account) { Address[] candidateAddress; Address[] listPostAddresses = ListHeaders.getListPostAddresses(message); Address[] replyToAddresses = message.getReplyTo(); Address[] fromAddresses = message.getFrom(); if (listPostAddresses.length > 0) { candidateAddress = listPostAddresses; } else 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); } | @Test public void getRecipientsToReplyListTo_should_prefer_listPost_over_from_field() throws Exception { when(message.getReplyTo()).thenReturn(EMPTY_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(LIST_POST_HEADER_VALUES); when(message.getFrom()).thenReturn(FROM_ADDRESSES); ReplyToAddresses result = replyToParser.getRecipientsToReplyListTo(message, account); assertArrayEquals(LIST_POST_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); verify(account).isAnIdentity(result.to); } |
ReplyToParser { public ReplyToAddresses getRecipientsToReplyAllTo(Message message, Account account) { List<Address> replyToAddresses = Arrays.asList(getRecipientsToReplyTo(message, account).to); HashSet<Address> alreadyAddedAddresses = new HashSet<>(replyToAddresses); ArrayList<Address> toAddresses = new ArrayList<>(replyToAddresses); ArrayList<Address> ccAddresses = new ArrayList<>(); for (Address address : message.getFrom()) { if (!alreadyAddedAddresses.contains(address) && !account.isAnIdentity(address)) { toAddresses.add(address); alreadyAddedAddresses.add(address); } } for (Address address : message.getRecipients(RecipientType.TO)) { if (!alreadyAddedAddresses.contains(address) && !account.isAnIdentity(address)) { toAddresses.add(address); alreadyAddedAddresses.add(address); } } for (Address address : message.getRecipients(RecipientType.CC)) { if (!alreadyAddedAddresses.contains(address) && !account.isAnIdentity(address)) { ccAddresses.add(address); alreadyAddedAddresses.add(address); } } return new ReplyToAddresses(toAddresses, ccAddresses); } ReplyToAddresses getRecipientsToReplyTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyAllTo(Message message, Account account); } | @Test public void getRecipientsToReplyAllTo_should_returnFromAndToAndCcRecipients() 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); when(message.getRecipients(RecipientType.TO)).thenReturn(TO_ADDRESSES); when(message.getRecipients(RecipientType.CC)).thenReturn(CC_ADDRESSES); ReplyToAddresses recipientsToReplyAllTo = replyToParser.getRecipientsToReplyAllTo(message, account); assertArrayEquals(arrayConcatenate(FROM_ADDRESSES, TO_ADDRESSES, Address.class), recipientsToReplyAllTo.to); assertArrayEquals(CC_ADDRESSES, recipientsToReplyAllTo.cc); }
@Test public void getRecipientsToReplyAllTo_should_excludeIdentityAddresses() throws Exception { when(message.getReplyTo()).thenReturn(EMPTY_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(new String[0]); when(message.getFrom()).thenReturn(EMPTY_ADDRESSES); when(message.getRecipients(RecipientType.TO)).thenReturn(TO_ADDRESSES); when(message.getRecipients(RecipientType.CC)).thenReturn(CC_ADDRESSES); Address excludedCcAddress = CC_ADDRESSES[1]; Address excludedToAddress = TO_ADDRESSES[0]; when(account.isAnIdentity(eq(excludedToAddress))).thenReturn(true); when(account.isAnIdentity(eq(excludedCcAddress))).thenReturn(true); ReplyToAddresses recipientsToReplyAllTo = replyToParser.getRecipientsToReplyAllTo(message, account); assertArrayEquals(arrayExcept(TO_ADDRESSES, excludedToAddress), recipientsToReplyAllTo.to); assertArrayEquals(arrayExcept(CC_ADDRESSES, excludedCcAddress), recipientsToReplyAllTo.cc); }
@Test public void getRecipientsToReplyAllTo_should_excludeDuplicates() throws Exception { when(message.getReplyTo()).thenReturn(REPLY_TO_ADDRESSES); when(message.getFrom()).thenReturn(arrayConcatenate(FROM_ADDRESSES, REPLY_TO_ADDRESSES, Address.class)); when(message.getRecipients(RecipientType.TO)).thenReturn(arrayConcatenate(FROM_ADDRESSES, TO_ADDRESSES, Address.class)); when(message.getRecipients(RecipientType.CC)).thenReturn(arrayConcatenate(CC_ADDRESSES, TO_ADDRESSES, Address.class)); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(new String[0]); ReplyToAddresses recipientsToReplyAllTo = replyToParser.getRecipientsToReplyAllTo(message, account); assertArrayContainsAll(REPLY_TO_ADDRESSES, recipientsToReplyAllTo.to); assertArrayContainsAll(FROM_ADDRESSES, recipientsToReplyAllTo.to); assertArrayContainsAll(TO_ADDRESSES, recipientsToReplyAllTo.to); int totalExpectedAddresses = REPLY_TO_ADDRESSES.length + FROM_ADDRESSES.length + TO_ADDRESSES.length; assertEquals(totalExpectedAddresses, recipientsToReplyAllTo.to.length); assertArrayEquals(CC_ADDRESSES, recipientsToReplyAllTo.cc); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.