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, fi...
@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( ...
@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(In...
@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 v...
@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...
@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*,...
@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.ap...
@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(...
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...
@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 saveStreamAsStr...
@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(verifyingKe...
@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) 2...
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 e...
@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.h...
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); stat...
@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( ...
@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 ...
@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 fal...
@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); assertEqu...
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()) ...
@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)...
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)) { retu...
@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]); ...
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 OA...
@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_");...
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 applyOAuthParam...
@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, "co...
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; ...
@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"); p...
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.con...
@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_");...
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(mess...
@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_"); par...
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 ...
@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 allowStringAsBinaryR...
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 ...
@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 createGi...
@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 OAuthClientR...
@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 .instantiateClassWithParamete...
@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 getOAut...
@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_TO...
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 getOAuthTok...
@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,...
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 ge...
@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,...
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 getRef...
@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.getSco...
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()...
@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_...
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 ha...
@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, ...
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 respons...
@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 ...
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 OA...
@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 getRefres...
@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 ...
@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 getO...
@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;...
@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", "7887323720...
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,...
@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, out...
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(re...
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 (isPartMultipartE...
@Test public void findEncryptedPartsShouldReturnMultipleEncryptedParts() throws Exception { MimeMessage message = new MimeMessage(); MimeMultipart multipartMixed = MimeMultipart.newInstance(); multipartMixed.setSubType("mixed"); MimeMessageHelper.setBody(message, multipartMixed); MimeMultipart multipartEncryptedOne = M...
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("...
@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(); r...
@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(...
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(mul...
@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...
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 = lo...
@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 ...
AttachmentInfoExtractor { public AttachmentViewInfo extractAttachmentInfoForDatabase(Part part) throws MessagingException { boolean isContentAvailable = part.getBody() != null; return extractAttachmentInfo(part, Uri.EMPTY, AttachmentViewInfo.UNKNOWN_SIZE, isContentAvailable); } @VisibleForTesting AttachmentInfoExtract...
@Test public void extractInfoForDb__withNoHeaders__shouldReturnEmptyValues() throws Exception { MimeBodyPart part = new MimeBodyPart(); AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part); assertEquals(Uri.EMPTY, attachmentViewInfo.internalUri); assertEquals(Attachment...
MessagePreviewCreator { public PreviewResult createPreview(@NonNull Message message) { if (encryptionDetector.isEncrypted(message)) { return PreviewResult.encrypted(); } return extractText(message); } MessagePreviewCreator(TextPartFinder textPartFinder, PreviewTextExtractor previewTextExtractor, EncryptionD...
@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...
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 Except...
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 plainTe...
@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 b...
PgpMessageBuilder extends MessageBuilder { public void setCryptoStatus(ComposeCryptoStatus cryptoStatus) { this.cryptoStatus = cryptoStatus; } @VisibleForTesting PgpMessageBuilder(Context context, MessageIdGenerator messageIdGenerator, BoundaryGenerator boundaryGenerator, AutocryptOperations autocryptOpera...
@Test public void build__withCryptoProviderUnconfigured__shouldThrow() throws MessagingException { cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE); cryptoStatusBuilder.setCryptoProviderState(CryptoProviderState.UNCONFIGURED); pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build()); Callback 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 ...
@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); ass...
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 IllegalStateExceptio...
@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.getDefaultDel...
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 enco...
@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 = Accoun...
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; } els...
@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_withNullArgument...
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 (...
@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 { con...
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...
@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).listFolde...
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.getLocalS...
@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(fa...
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.getPreference...
@Test public void searchLocalMessagesSynchronous_shouldCallSearchForMessagesOnLocalStore() throws Exception { setAccountsInPreferences(Collections.singletonMap("1", account)); when(search.getAccountUuids()).thenReturn(new String[]{"allAccounts"}); controller.searchLocalMessagesSynchronous(search, listener); verify(loca...
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.is...
@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(pgpInline...
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(cont...
@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...
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 fals...
@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-...
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( accoun...
@Test public void sendPendingMessagesSynchronous_shouldCallListenerOnStart() throws MessagingException { setupAccountWithMessageToSend(); controller.sendPendingMessagesSynchronous(account); verify(listener).sendPendingMessagesStarted(account); } @Test public void sendPendingMessagesSynchronous_shouldSetProgress() throw...
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....
@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, FOL...
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 = findPrimaryPartInMix...
@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(mess...
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 transferEn...
@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(); ass...
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....
@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(...
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, ...
@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); a...
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 DeferredFile...
@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 DeferredFile...
@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 ...
@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. Reset...
@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 databa...
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(oldPend...
@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 migratePendi...
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(oldPendingCom...
@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_...
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 inst...
@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(Html...
MessageViewInfoExtractor { @WorkerThread public MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations cryptoAnnotations) throws MessagingException { ArrayList<Part> extraParts = new ArrayList<>(); Part cryptoContentPart = MessageCryptoStructureDetector.findPrimaryEncryptedOrSignedPar...
@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); setupAttach...
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 = p...
@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__shouldR...
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);...
@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 se...
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).ap...
@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; keydat...
AutocryptHeaderParser { @Nullable AutocryptHeader getValidAutocryptHeader(Message currentMessage) { String[] headers = currentMessage.getHeader(AutocryptHeader.AUTOCRYPT_HEADER); ArrayList<AutocryptHeader> autocryptHeaders = parseAllAutocryptHeaders(headers); boolean isSingleValidHeader = autocryptHeaders.size() == 1; ...
@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 getValidAutocry...
MessageCryptoHelper { public void asyncStartOrResumeProcessingMessage(Message message, MessageCryptoCallback callback, OpenPgpDecryptionResult cachedOpenPgpDecryptionResult, SMimeDecryptionResult cachedSMimeDecryptionResult, boolean processSignedOnly) { if (this.currentMessage != null) { reattachCallback(message, callb...
@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); messageCryp...
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 ...
@Test public void findEncryptedPartsShouldReturnEmptyListForEmptyMessage() throws Exception { MimeMessage emptyMessage = new MimeMessage(); List<Part> encryptedParts = MessageCryptoStructureDetector.findMultipartEncryptedParts(emptyMessage); assertEquals(0, encryptedParts.size()); } @Test public void findEncryptedParts...
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); sIns...
@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_re...
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...
@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 EmailProviderCa...
@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 synch...
@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; bre...
@Test public void testXOriginalTo() throws Exception { Address[] addresses = {new Address("test2@mail.com")}; msg.setRecipients(Message.RecipientType.X_ORIGINAL_TO, addresses); Identity identity = IdentityHelper.getRecipientIdentityFromMessage(account, msg); assertTrue(identity.getEmail().equalsIgnoreCase("test2@mail.c...
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 K9Alar...
@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_shouldCallSetOnAlarm...
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(...
@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[] p...
@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 stripN...
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...
@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 ...
@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.cl...
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(); Strin...
@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 getB...
@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(Strin...
@Test public void getDomainFromEmailAddress_withRegularEmail_shouldReturnsDomain() { String result = EmailHelper.getDomainFromEmailAddress("user@domain.com"); assertEquals("domain.com", result); } @Test public void getDomainFromEmailAddress_withInvalidEmail_shouldReturnNull() { String result = EmailHelper.getDomainFrom...
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(fin...
@Test public void testToFriendlyShowsPersonalPartIfItExists() throws Exception { Address address = new Address("test@testor.com", "Tim Testor"); assertEquals("Tim Testor", MessageHelper.toFriendly(address, contacts)); } @Test public void testToFriendlyShowsEmailPartIfNoPersonalPartExists() throws Exception { Address ad...
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...
@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); ReplyToAddres...
ReplyToParser { public ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account) { Address[] candidateAddress; Address[] listPostAddresses = ListHeaders.getListPostAddresses(message); Address[] replyToAddresses = message.getReplyTo(); Address[] fromAddresses = message.getFrom(); if (listPostAddresse...
@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...
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<>(re...
@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(R...