target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testShowSendFailedNotification() throws Exception { Exception exception = new Exception(); sendFailedNotifications.showSendFailedNotification(account, exception); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setTicker("Failed to send some messages"); verify(builder).setContentTitle("Failed to send some messages"); verify(builder).setContentText("Exception"); verify(builder).setContentIntent(contentIntent); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); }
public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); }
SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } }
SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); }
SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }
SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }
@Test public void testClearSendFailedNotification() throws Exception { sendFailedNotifications.clearSendFailedNotification(account); verify(notificationManager).cancel(notificationId); }
public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); }
SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } }
SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); }
SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }
SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); }
@Test public void testAddNotificationContent() throws Exception { NotificationContent content = createNotificationContent("1"); AddNotificationResult result = notificationData.addNotificationContent(content); assertFalse(result.shouldCancelNotification()); NotificationHolder holder = result.getNotificationHolder(); assertNotNull(holder); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), holder.notificationId); assertEquals(content, holder.content); }
public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testAddNotificationContentWithReplacingNotification() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); notificationData.addNotificationContent(createNotificationContent("2")); notificationData.addNotificationContent(createNotificationContent("3")); notificationData.addNotificationContent(createNotificationContent("4")); notificationData.addNotificationContent(createNotificationContent("5")); notificationData.addNotificationContent(createNotificationContent("6")); notificationData.addNotificationContent(createNotificationContent("7")); notificationData.addNotificationContent(createNotificationContent("8")); AddNotificationResult result = notificationData.addNotificationContent(createNotificationContent("9")); assertTrue(result.shouldCancelNotification()); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), result.getNotificationId()); }
public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void findSigned__withEmptyProtocol__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", bodypart("text/plain", "content"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertTrue(signedParts.isEmpty()); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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 testRemoveNotificationForMessage() throws Exception { NotificationContent content = createNotificationContent("1"); notificationData.addNotificationContent(content); RemoveNotificationResult result = notificationData.removeNotificationForMessage(content.messageReference); assertFalse(result.isUnknownNotification()); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), result.getNotificationId()); assertFalse(result.shouldCreateNotification()); }
public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); }
NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } }
NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } NotificationData(Account account); }
NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testContainsStarredMessages() throws Exception { assertFalse(notificationData.containsStarredMessages()); notificationData.addNotificationContent(createNotificationContentForStarredMessage()); assertTrue(notificationData.containsStarredMessages()); }
public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; }
NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } }
NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } NotificationData(Account account); }
NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testIsSingleMessageNotification() throws Exception { assertFalse(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("1")); assertTrue(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("2")); assertFalse(notificationData.isSingleMessageNotification()); }
public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; }
NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } }
NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } NotificationData(Account account); }
NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testGetContentForSummaryNotification() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); NotificationContent content4 = createNotificationContent("2"); notificationData.addNotificationContent(content4); NotificationContent content3 = createNotificationContent("3"); notificationData.addNotificationContent(content3); NotificationContent content2 = createNotificationContent("4"); notificationData.addNotificationContent(content2); NotificationContent content1 = createNotificationContent("5"); notificationData.addNotificationContent(content1); NotificationContent content0 = createNotificationContent("6"); notificationData.addNotificationContent(content0); List<NotificationContent> contents = notificationData.getContentForSummaryNotification(); assertEquals(5, contents.size()); assertEquals(content0, contents.get(0)); assertEquals(content1, contents.get(1)); assertEquals(content2, contents.get(2)); assertEquals(content3, contents.get(3)); assertEquals(content4, contents.get(4)); }
public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; }
NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } }
NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } NotificationData(Account account); }
NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testGetActiveNotificationIds() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); notificationData.addNotificationContent(createNotificationContent("2")); int[] notificationIds = notificationData.getActiveNotificationIds(); assertEquals(2, notificationIds.length); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 1), notificationIds[0]); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), notificationIds[1]); }
public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; }
NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } }
NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } NotificationData(Account account); }
NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testGetAccount() throws Exception { assertEquals(account, notificationData.getAccount()); }
public Account getAccount() { return account; }
NotificationData { public Account getAccount() { return account; } }
NotificationData { public Account getAccount() { return account; } NotificationData(Account account); }
NotificationData { public Account getAccount() { return account; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public Account getAccount() { return account; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testGetAllMessageReferences() throws Exception { MessageReference messageReference0 = createMessageReference("1"); MessageReference messageReference1 = createMessageReference("2"); MessageReference messageReference2 = createMessageReference("3"); MessageReference messageReference3 = createMessageReference("4"); MessageReference messageReference4 = createMessageReference("5"); MessageReference messageReference5 = createMessageReference("6"); MessageReference messageReference6 = createMessageReference("7"); MessageReference messageReference7 = createMessageReference("8"); MessageReference messageReference8 = createMessageReference("9"); notificationData.addNotificationContent(createNotificationContent(messageReference8)); notificationData.addNotificationContent(createNotificationContent(messageReference7)); notificationData.addNotificationContent(createNotificationContent(messageReference6)); notificationData.addNotificationContent(createNotificationContent(messageReference5)); notificationData.addNotificationContent(createNotificationContent(messageReference4)); notificationData.addNotificationContent(createNotificationContent(messageReference3)); notificationData.addNotificationContent(createNotificationContent(messageReference2)); notificationData.addNotificationContent(createNotificationContent(messageReference1)); notificationData.addNotificationContent(createNotificationContent(messageReference0)); List<MessageReference> messageReferences = notificationData.getAllMessageReferences(); assertEquals(9, messageReferences.size()); assertEquals(messageReference0, messageReferences.get(0)); assertEquals(messageReference1, messageReferences.get(1)); assertEquals(messageReference2, messageReferences.get(2)); assertEquals(messageReference3, messageReferences.get(3)); assertEquals(messageReference4, messageReferences.get(4)); assertEquals(messageReference5, messageReferences.get(5)); assertEquals(messageReference6, messageReferences.get(6)); assertEquals(messageReference7, messageReferences.get(7)); assertEquals(messageReference8, messageReferences.get(8)); }
public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; }
NotificationData { public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; } }
NotificationData { public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; } NotificationData(Account account); }
NotificationData { public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
NotificationData { public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); }
@Test public void testAddNewMailNotification() throws Exception { int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification wearNotification = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holder, wearNotification); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationId, wearNotification); verify(notificationManager).notify(summaryNotificationId, summaryNotification); }
public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testAddNewMailNotificationWithCancelingExistingNotification() throws Exception { int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.replaceNotification(holder)); Notification wearNotification = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holder, wearNotification); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationId, wearNotification); verify(notificationManager).cancel(wearNotificationId); verify(notificationManager).notify(summaryNotificationId, summaryNotification); }
public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testAddNewMailNotificationWithPrivacyModeEnabled() throws Exception { enablePrivacyMode(); int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification wearNotification = createNotification(); addToDeviceNotifications(wearNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager, never()).notify(eq(wearNotificationId), any(Notification.class)); verify(notificationManager).notify(summaryNotificationId, wearNotification); }
public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void findSigned__withMissingSignature__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertTrue(signedParts.isEmpty()); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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 testAddNewMailNotificationTwice() throws Exception { int notificationIndexOne = 0; int notificationIndexTwo = 1; LocalMessage messageOne = createLocalMessage(); LocalMessage messageTwo = createLocalMessage(); NotificationContent contentOne = createNotificationContent(); NotificationContent contentTwo = createNotificationContent(); NotificationHolder holderOne = createNotificationHolder(contentOne, notificationIndexOne); NotificationHolder holderTwo = createNotificationHolder(contentTwo, notificationIndexTwo); addToNotificationContentCreator(messageOne, contentOne); addToNotificationContentCreator(messageTwo, contentTwo); whenAddingContentReturn(contentOne, AddNotificationResult.newNotification(holderOne)); whenAddingContentReturn(contentTwo, AddNotificationResult.newNotification(holderTwo)); Notification wearNotificationOne = createNotification(); Notification wearNotificationTwo = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holderOne, wearNotificationOne); addToWearNotifications(holderTwo, wearNotificationTwo); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, messageOne, 42); newMailNotifications.addNewMailNotification(account, messageTwo, 42); int wearNotificationIdOne = NotificationIds.getNewMailStackedNotificationId(account, notificationIndexOne); int wearNotificationIdTwo = NotificationIds.getNewMailStackedNotificationId(account, notificationIndexTwo); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationIdOne, wearNotificationOne); verify(notificationManager).notify(wearNotificationIdTwo, wearNotificationTwo); verify(notificationManager, times(2)).notify(summaryNotificationId, summaryNotification); }
public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testRemoveNewMailNotificationWithoutNotificationData() throws Exception { MessageReference messageReference = createMessageReference(1); newMailNotifications.removeNewMailNotification(account, messageReference); verify(notificationManager, never()).cancel(anyInt()); }
public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testRemoveNewMailNotification() throws Exception { enablePrivacyMode(); MessageReference messageReference = createMessageReference(1); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification summaryNotification = createNotification(); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 23); whenRemovingContentReturn(messageReference, RemoveNotificationResult.cancelNotification(notificationId)); newMailNotifications.removeNewMailNotification(account, messageReference); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).cancel(notificationId); verify(notificationManager, times(2)).notify(summaryNotificationId, summaryNotification); }
public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testClearNewMailNotificationsWithoutNotificationData() throws Exception { newMailNotifications.clearNewMailNotifications(account); verify(notificationManager, never()).cancel(anyInt()); }
public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testClearNewMailNotifications() throws Exception { int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); setActiveNotificationIds(notificationId); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); newMailNotifications.addNewMailNotification(account, message, 3); newMailNotifications.clearNewMailNotifications(account); verify(notificationManager).cancel(notificationId); verify(notificationManager).cancel(NotificationIds.getNewMailSummaryNotificationId(account)); }
public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator, DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller, NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); }
@Test public void testShowCertificateErrorNotificationForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.showCertificateErrorNotification(account, INCOMING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); }
public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
@Test public void testClearCertificateErrorNotificationsForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.clearCertificateErrorNotifications(account, INCOMING); verify(notificationManager).cancel(notificationId); }
public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
@Test public void testShowCertificateErrorNotificationForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.showCertificateErrorNotification(account, OUTGOING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); }
public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
@Test public void testClearCertificateErrorNotificationsForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.clearCertificateErrorNotifications(account, OUTGOING); verify(notificationManager).cancel(notificationId); }
public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); }
@Test public void suggestServerName_forImapServer() throws Exception { Type serverType = Type.IMAP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("imap.example.org", result); }
public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
@Test public void findSigned__withComplexMultipartSigned__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", multipart("mixed", bodypart("text/plain"), bodypart("application/pdf") ), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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 suggestServerName_forPop3Server() throws Exception { Type serverType = Type.POP3; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("pop3.example.org", result); }
public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
@Test public void suggestServerName_forWebDavServer() throws Exception { Type serverType = Type.WebDAV; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("exchange.example.org", result); }
public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
@Test public void suggestServerName_forSmtpServer() throws Exception { Type serverType = Type.SMTP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("smtp.example.org", result); }
public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); }
@Test public void wasMessageTransmittedSecurely_withNoHeaders_shouldReturnUnknown() throws MessagingException { String[] noReceivedHeaders = new String[]{}; Message unknownMessage = mock(Message.class); when(unknownMessage.getHeader("Received")).thenReturn(noReceivedHeaders); assertEquals(SecureTransportError.UNKNOWN, ReceivedHeaders.wasMessageTransmittedSecurely(unknownMessage).getErrorType()); }
public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); static final String RECEIVED; static Pattern fromPattern; static Pattern byPattern; static Pattern usingPattern; static final String AUTHENTICATION_RESULTS; static Pattern spfPattern; static Pattern dkimPattern; }
@Test public void wasMessageTransmittedSecurely_forInsecureMessage_shouldReturnFalse() throws MessagingException { String[] insecureReceivedHeaders = new String[]{ " from localhost (localhost [127.0.0.1])\n" + "by scarlet.richardwhiuk.com (Postfix)\n " + "with ESMTP id BB1057BA98\n " + "for <[email protected]>; Fri, 25 Mar 2016 10:38:29 +0000 (GMT)", " from scarlet.richardwhiuk.com ([127.0.0.1])\n" + "by localhost (scarlet.richardwhiuk.com [127.0.0.1]) (amavisd-new, port 10024)\n" + "with ESMTP id kEaYiQPLCxiT for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk (serpentine.unitedhosting.co.uk [83.223.125.16])\n" + "(using SSL with cipher DHE-RSA-AES256-SHA (256/256 bits))\n" + "(No client certificate requested)\n" + "by scarlet.richardwhiuk.com (Postfix)\n" + "with ESMTPS id C19917A8E9\n" + "for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk ([83.223.125.16]:56654 helo=serpentine.org.uk)\n" + "by serpentine.unitedhosting.co.uk\n" + "with esmtp (Exim 4.86_1) (envelope-from <[email protected]>)\n" + "id 1ajOr6-00020j-MM\n" + "for [email protected]; Fri, 25 Mar 2016 10:20:36 +0000\n" }; Message insecureMessage = mock(Message.class); when(insecureMessage.getHeader("Received")).thenReturn(insecureReceivedHeaders); assertEquals(SecureTransportError.INSECURELY_ENCRYPTED, ReceivedHeaders.wasMessageTransmittedSecurely(insecureMessage).getErrorType()); }
public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); static final String RECEIVED; static Pattern fromPattern; static Pattern byPattern; static Pattern usingPattern; static final String AUTHENTICATION_RESULTS; static Pattern spfPattern; static Pattern dkimPattern; }
@Test public void wasMessageTransmittedSecurely_forSecureMessage_shouldReturnTrue() throws MessagingException { String[] secureReceivedHeaders = new String[]{ " from localhost (localhost [127.0.0.1])\n" + "by scarlet.richardwhiuk.com (Postfix)\n " + "with ESMTP id BB1057BA98\n " + "for <[email protected]>; Fri, 25 Mar 2016 10:38:29 +0000 (GMT)", " from scarlet.richardwhiuk.com ([127.0.0.1])\n" + "by localhost (scarlet.richardwhiuk.com [127.0.0.1]) (amavisd-new, port 10024)\n" + "with ESMTP id kEaYiQPLCxiT for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk (serpentine.unitedhosting.co.uk [83.223.125.16])\n" + "(using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits))\n" + "(No client certificate requested)\n" + "by scarlet.richardwhiuk.com (Postfix)\n" + "with ESMTPS id C19917A8E9\n" + "for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk ([83.223.125.16]:56654 helo=serpentine.org.uk)\n" + "by serpentine.unitedhosting.co.uk\n" + "with esmtp (Exim 4.86_1) (envelope-from <[email protected]>)\n" + "id 1ajOr6-00020j-MM\n" + "for [email protected]; Fri, 25 Mar 2016 10:20:36 +0000\n" }; Message secureMessage = mock(Message.class); when(secureMessage.getHeader("Received")).thenReturn(secureReceivedHeaders); assertEquals(SecureTransportError.SECURELY_ENCRYPTED, ReceivedHeaders.wasMessageTransmittedSecurely(secureMessage).getErrorType()); }
public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); }
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); static final String RECEIVED; static Pattern fromPattern; static Pattern byPattern; static Pattern usingPattern; static final String AUTHENTICATION_RESULTS; static Pattern spfPattern; static Pattern dkimPattern; }
@Test public void exportPreferences_producesXML() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals("k9settings", document.getRootElement().getName()); }
static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
@Test public void exportPreferences_setsVersionToLatest() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals(Integer.toString(Settings.VERSION), document.getRootElement().getAttributeValue("version")); }
static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
@Test public void exportPreferences_setsFormatTo1() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals("1", document.getRootElement().getAttributeValue("format")); }
static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
@Test public void exportPreferences_exportsGlobalSettingsWhenRequested() throws Exception { Document document = exportPreferences(true, Collections.<String>emptySet()); assertNotNull(document.getRootElement().getChild("global")); }
static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
@Test public void findEncrypted__withMultipartMixedSubSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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_withEmptyMultipartAlternative_shouldReturnNull() throws Exception { List<Part> outputExtraParts = new ArrayList<>(); Message message = messageFromBody( multipart("alternative") ); Part cryptoPart = MessageDecryptVerifier.findPrimaryEncryptedOrSignedPart(message, outputExtraParts); assertNull(cryptoPart); }
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; }
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; } }
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; } }
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); }
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 exportPreferences_ignoresGlobalSettingsWhenRequested() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertNull(document.getRootElement().getChild("global")); }
static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnBlankFile() throws SettingsImportExportException { InputStream inputStream = new StringInputStream(""); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnMissingFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnInvalidFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\" format=\"A\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnNonPositiveFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\" format=\"0\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnMissingVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnInvalidVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"A\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnNonPositiveVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"0\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void parseSettings_account() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name></account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add("1"); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, true); assertEquals(1, results.accounts.size()); assertEquals("Account", results.accounts.get(validUUID).name); assertEquals(validUUID, results.accounts.get(validUUID).uuid); }
@VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void parseSettings_account_identities() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<identities><identity><email>[email protected]</email></identity></identities>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add("1"); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, true); assertEquals(1, results.accounts.size()); assertEquals(validUUID, results.accounts.get(validUUID).uuid); assertEquals(1, results.accounts.get(validUUID).identities.size()); assertEquals("[email protected]", results.accounts.get(validUUID).identities.get(0).email); }
@VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void findEncrypted__withMultipartMixedSubSignedAndText__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", "application/pgp-signature", bodypart("text/plain"), bodypart("application/pgp-signature") ), bodypart("text/plain") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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 parseSettings_account_cram_md5() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<incoming-server><authentication-type>CRAM_MD5</authentication-type></incoming-server>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add(validUUID); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, false); assertEquals("Account", results.accounts.get(validUUID).name); assertEquals(validUUID, results.accounts.get(validUUID).uuid); assertEquals(AuthType.CRAM_MD5, results.accounts.get(validUUID).incoming.authenticationType); }
@VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void importSettings_disablesAccountsNeedingPasswords() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<incoming-server type=\"IMAP\">" + "<connection-security>SSL_TLS_REQUIRED</connection-security>" + "<username>[email protected]</username>" + "<authentication-type>CRAM_MD5</authentication-type>" + "<host>googlemail.com</host>" + "</incoming-server>" + "<outgoing-server type=\"SMTP\">" + "<connection-security>SSL_TLS_REQUIRED</connection-security>" + "<username>[email protected]</username>" + "<authentication-type>CRAM_MD5</authentication-type>" + "<host>googlemail.com</host>" + "</outgoing-server>" + "<settings><value key=\"a\">b</value></settings>" + "<identities><identity><email>[email protected]</email></identity></identities>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add(validUUID); SettingsImporter.ImportResults results = SettingsImporter.importSettings( RuntimeEnvironment.application, inputStream, true, accountUuids, false); assertEquals(0, results.erroneousAccounts.size()); assertEquals(1, results.importedAccounts.size()); assertEquals("Account", results.importedAccounts.get(0).imported.name); assertEquals(validUUID, results.importedAccounts.get(0).imported.uuid); assertFalse(Preferences.getPreferences(RuntimeEnvironment.application) .getAccount(validUUID).isEnabled()); }
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void getImportStreamContents_account() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts>" + "<account uuid=\"" + validUUID + "\">" + "<name>Account</name>" + "<identities>" + "<identity>" + "<email>[email protected]</email>" + "</identity>" + "</identities>" + "</account>" + "</accounts></k9settings>"); SettingsImporter.ImportContents results = SettingsImporter.getImportStreamContents(inputStream); assertEquals(false, results.globalSettings); assertEquals(1, results.accounts.size()); assertEquals("Account", results.accounts.get(0).name); assertEquals(validUUID, results.accounts.get(0).uuid); }
public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void getImportStreamContents_alternativeName() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts>" + "<account uuid=\"" + validUUID + "\">" + "<name></name>" + "<identities>" + "<identity>" + "<email>[email protected]</email>" + "</identity>" + "</identities>" + "</account>" + "</accounts></k9settings>"); SettingsImporter.ImportContents results = SettingsImporter.getImportStreamContents(inputStream); assertEquals(false, results.globalSettings); assertEquals(1, results.accounts.size()); assertEquals("[email protected]", results.accounts.get(0).name); assertEquals(validUUID, results.accounts.get(0).uuid); }
public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite); }
@Test public void ICalendar_constructor_storedRequiredAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.REQUIRED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getRequired()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void ICalendar_constructor_storedOptionalAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.OPTIONAL); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getOptional()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void ICalendar_constructor_storedFyiAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.FYI); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getFyi()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void ICalendar_constructor_storedAcceptedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.ACCEPTED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getAccepted()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void ICalendar_constructor_storedTentativeAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.TENTATIVE); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getTentative()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void ICalendar_constructor_storedDeclinedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.DECLINED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getDeclined()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void findEncrypted__withMultipartMixedSubTextAndSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("signed", "application/pgp-signature", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 1), signedParts.get(0)); }
public static List<Part> findMultipartSignedParts(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; }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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; } }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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); }
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(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> 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 ICalendar_constructor_storedDelegatedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.DELEGATED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getDelegated()[0]); }
public List<ICalendarData> getCalendarData() { return calendarData; }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); }
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; }
@Test public void parse_withNoText_returnsDataWithNoEvents() throws MessagingException { ICalPart part = new ICalPart(null); ICalData data = ICalParser.parse(part); assertEquals(0, data.getCalendarData().size()); }
public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } static ICalData parse(ICalPart part); }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } static ICalData parse(ICalPart part); static final String MIME_TYPE; }
@Test public void parse_returnsCorrectDataForMinimalPublishEvent() throws MessagingException { String calendar = "BEGIN:VCALENDAR\r\n" + "METHOD:PUBLISH\r\n" + "PRODID:-"VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "ORGANIZER:mailto:[email protected]\r\n" + "DTSTART:19970701T200000Z\r\n" + "DTSTAMP:19970611T190000Z\r\n" + "SUMMARY:ST. PAUL SAINTS -VS- DULUTH-SUPERIOR DUKES\r\n" + "UID:[email protected]\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR"; Body body = new TextBody(calendar); MimeBodyPart dataPart = new MimeBodyPart(body); ICalPart part = new ICalPart(dataPart); ICalData data = ICalParser.parse(part); assertEquals(1, data.getCalendarData().size()); assertEquals("PUBLISH", data.getCalendarData().get(0).getMethod().getValue()); assertEquals("[email protected]", data.getCalendarData().get(0).getOrganizer().getEmail()); }
public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } static ICalData parse(ICalPart part); }
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } static ICalData parse(ICalPart part); static final String MIME_TYPE; }
@Test public void decodeTransportUri_canDecodeAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(AuthType.PLAIN, result.authenticationType); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeUsername() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodePassword() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("password", result.password); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeUsername_withNoAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeUsername_withNoPasswordOrAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeAuthType_withEmptyPassword() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(AuthType.PLAIN, result.authenticationType); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeHost() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("server", result.host); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@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(MessageCryptoStructureDetector.isPartPgpInlineEncrypted(message)); }
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); }
MessageCryptoStructureDetector { 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); } }
MessageCryptoStructureDetector { 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); } }
MessageCryptoStructureDetector { 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> 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); }
MessageCryptoStructureDetector { 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> 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 decodeTransportUri_canDecodePort() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(123456, result.port); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeTLS() { String storeUri = "smtp+tls+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(ConnectionSecurity.STARTTLS_REQUIRED, result.connectionSecurity); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeSSL() { String storeUri = "smtp+ssl+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(ConnectionSecurity.SSL_TLS_REQUIRED, result.connectionSecurity); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void decodeTransportUri_canDecodeClientCert() { String storeUri = "smtp+ssl+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("clientCert", result.clientCertificateAlias); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test(expected = IllegalArgumentException.class) public void decodeTransportUri_forUnknownSchema_throwsIllegalArgumentException() { String storeUri = "unknown: TransportUris.decodeTransportUri(storeUri); }
public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void createTransportUri_canEncodeSmtpSslUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.EXTERNAL, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+ssl+: }
public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void createTransportUri_canEncodeSmtpTlsUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.STARTTLS_REQUIRED, AuthType.PLAIN, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+tls+: }
public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void createTransportUri_canEncodeSmtpUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.NONE, AuthType.CRAM_MD5, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp: }
public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); }
@Test public void open_withoutAuthLoginExtension_shouldConnectWithoutAuthentication() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 OK"); SmtpTransport transport = startServerAndCreateSmtpTransportWithoutPassword(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withAuthPlainExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("AUTH PLAIN AHVzZXIAcGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@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(MessageCryptoStructureDetector.isPartPgpInlineEncryptedOrSigned(message)); }
@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); }
MessageCryptoStructureDetector { @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); } }
MessageCryptoStructureDetector { @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); } }
MessageCryptoStructureDetector { @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> 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); }
MessageCryptoStructureDetector { @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> 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 open_withAuthLoginExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH LOGIN"); server.expect("AUTH LOGIN"); server.output("250 OK"); server.expect("dXNlcg=="); server.output("250 OK"); server.expect("cGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withoutLoginAndPlainAuthExtensions_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication methods SASL PLAIN and LOGIN are unavailable.", e.getMessage()); } server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withCramMd5AuthExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH CRAM-MD5"); server.expect("AUTH CRAM-MD5"); server.output(Base64.encode("<24609.1047914046@localhost>")); server.expect("dXNlciA3NmYxNWEzZmYwYTNiOGI1NzcxZmNhODZlNTcyMDk2Zg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.CRAM_MD5, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withoutCramMd5AuthExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.CRAM_MD5, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication method CRAM-MD5 is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension_shouldThrowOn401Response() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.STATUS_401_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals( "5.7.1 Username and Password not accepted. Learn more at " + "5.7.1 http: e.getMessage()); } InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOn400Response() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOnInvalidJsonResponse() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.INVALID_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOnMissingStatusJsonResponse() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.MISSING_STATUS_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withXoauth2Extension_shouldThrowOnMultipleFailure() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 " + XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("334 " + XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals( "5.7.1 Username and Password not accepted. Learn more at " + "5.7.1 http: e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@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(MessageCryptoStructureDetector.isPartPgpInlineEncrypted(message)); }
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); }
MessageCryptoStructureDetector { 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); } }
MessageCryptoStructureDetector { 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); } }
MessageCryptoStructureDetector { 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> 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); }
MessageCryptoStructureDetector { 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> 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 open_withXoauth2Extension_shouldThrowOnFailure_fetchingToken() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("QUIT"); server.output("221 BYE"); when(oAuth2TokenProvider.getToken(anyString(), anyInt())).thenThrow(new AuthenticationFailedException("Failed to fetch token")); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals("Failed to fetch token", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withoutXoauth2Extension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication method XOAUTH2 is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withAuthExternalExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH EXTERNAL"); server.expect("AUTH EXTERNAL dXNlcg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.EXTERNAL, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withoutAuthExternalExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.EXTERNAL, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (CertificateValidationException e) { assertEquals(CertificateValidationException.Reason.MissingCapability, e.getReason()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withAutomaticAuthAndNoTransportSecurityAndAuthCramMd5Extension_shouldUseAuthCramMd5() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH CRAM-MD5"); server.expect("AUTH CRAM-MD5"); server.output(Base64.encode("<24609.1047914046@localhost>")); server.expect("dXNlciA3NmYxNWEzZmYwYTNiOGI1NzcxZmNhODZlNTcyMDk2Zg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.AUTOMATIC, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
@Test public void open_withAutomaticAuthAndNoTransportSecurityAndAuthPlainExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.AUTOMATIC, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory, OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); }