Search in sources :

Example 26 with VisibleForTesting

use of android.support.annotation.VisibleForTesting in project mobile-center-sdk-android by Microsoft.

the class Crashes method buildErrorReport.

@VisibleForTesting
@Nullable
ErrorReport buildErrorReport(ManagedErrorLog log) {
    UUID id = log.getId();
    if (mErrorReportCache.containsKey(id)) {
        return mErrorReportCache.get(id).report;
    } else {
        File file = ErrorLogHelper.getStoredThrowableFile(id);
        if (file != null) {
            try {
                Throwable throwable = null;
                if (file.length() > 0) {
                    throwable = StorageHelper.InternalStorage.readObject(file);
                }
                ErrorReport report = ErrorLogHelper.getErrorReportFromErrorLog(log, throwable);
                mErrorReportCache.put(id, new ErrorLogReport(log, report));
                return report;
            } catch (ClassNotFoundException ignored) {
                AppCenterLog.error(LOG_TAG, "Cannot read throwable file " + file.getName(), ignored);
            } catch (IOException ignored) {
                AppCenterLog.error(LOG_TAG, "Cannot access serialized throwable file " + file.getName(), ignored);
            }
        }
    }
    return null;
}
Also used : ErrorReport(com.microsoft.appcenter.crashes.model.ErrorReport) IOException(java.io.IOException) UUID(java.util.UUID) File(java.io.File) VisibleForTesting(android.support.annotation.VisibleForTesting) Nullable(android.support.annotation.Nullable)

Example 27 with VisibleForTesting

use of android.support.annotation.VisibleForTesting in project mobile-center-sdk-android by Microsoft.

the class Distribute method getLatestReleaseDetails.

/**
 * Get latest release details from server.
 *
 * @param distributionGroupId distribution group id.
 * @param updateToken         token to secure API call.
 */
@VisibleForTesting
synchronized void getLatestReleaseDetails(String distributionGroupId, String updateToken) {
    AppCenterLog.debug(LOG_TAG, "Get latest release details...");
    HttpClientRetryer retryer = new HttpClientRetryer(new DefaultHttpClient());
    NetworkStateHelper networkStateHelper = NetworkStateHelper.getSharedInstance(mContext);
    HttpClient httpClient = new HttpClientNetworkStateHandler(retryer, networkStateHelper);
    String releaseHash = computeReleaseHash(mPackageInfo);
    String url = mApiUrl;
    if (updateToken == null) {
        url += String.format(GET_LATEST_PUBLIC_RELEASE_PATH_FORMAT, mAppSecret, distributionGroupId, releaseHash, getReportingParametersForUpdatedRelease(true, ""));
    } else {
        url += String.format(GET_LATEST_PRIVATE_RELEASE_PATH_FORMAT, mAppSecret, releaseHash, getReportingParametersForUpdatedRelease(false, distributionGroupId));
    }
    Map<String, String> headers = new HashMap<>();
    if (updateToken != null) {
        headers.put(HEADER_API_TOKEN, updateToken);
    }
    final Object releaseCallId = mCheckReleaseCallId = new Object();
    mCheckReleaseApiCall = httpClient.callAsync(url, METHOD_GET, headers, new HttpClient.CallTemplate() {

        @Override
        public String buildRequestBody() throws JSONException {
            /* Only GET is used by Distribute service. This method is never getting called. */
            return null;
        }

        @Override
        public void onBeforeCalling(URL url, Map<String, String> headers) {
            if (AppCenterLog.getLogLevel() <= VERBOSE) {
                /* Log url. */
                String urlString = url.toString().replaceAll(mAppSecret, HttpUtils.hideSecret(mAppSecret));
                AppCenterLog.verbose(LOG_TAG, "Calling " + urlString + "...");
                /* Log headers. */
                Map<String, String> logHeaders = new HashMap<>(headers);
                String apiToken = logHeaders.get(HEADER_API_TOKEN);
                if (apiToken != null) {
                    logHeaders.put(HEADER_API_TOKEN, HttpUtils.hideSecret(apiToken));
                }
                AppCenterLog.verbose(LOG_TAG, "Headers: " + logHeaders);
            }
        }
    }, new ServiceCallback() {

        @Override
        public void onCallSucceeded(final String payload) {
            /* onPostExecute is not always called on UI thread due to an old Android bug. */
            HandlerUtils.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        handleApiCallSuccess(releaseCallId, payload, ReleaseDetails.parse(payload));
                    } catch (JSONException e) {
                        onCallFailed(e);
                    }
                }
            });
        }

        @Override
        public void onCallFailed(Exception e) {
            handleApiCallFailure(releaseCallId, e);
        }
    });
}
Also used : HashMap(java.util.HashMap) JSONException(org.json.JSONException) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient) DEFAULT_INSTALL_URL(com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_INSTALL_URL) DEFAULT_API_URL(com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_API_URL) URL(java.net.URL) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) HttpException(com.microsoft.appcenter.http.HttpException) ActivityNotFoundException(android.content.ActivityNotFoundException) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) HttpClientRetryer(com.microsoft.appcenter.http.HttpClientRetryer) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient) HttpClient(com.microsoft.appcenter.http.HttpClient) NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) Map(java.util.Map) HashMap(java.util.HashMap) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 28 with VisibleForTesting

use of android.support.annotation.VisibleForTesting in project android-testing by googlesamples.

the class ContactsActivity method createResultData.

@VisibleForTesting
static Intent createResultData(String phoneNumber) {
    final Intent resultData = new Intent();
    resultData.putExtra(KEY_PHONE_NUMBER, phoneNumber);
    return resultData;
}
Also used : Intent(android.content.Intent) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 29 with VisibleForTesting

use of android.support.annotation.VisibleForTesting in project k-9 by k9mail.

the class MessagingController method searchRemoteMessagesSynchronous.

@VisibleForTesting
void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query, final Set<Flag> requiredFlags, final Set<Flag> forbiddenFlags, final MessagingListener listener) {
    final Account acct = Preferences.getPreferences(context).getAccount(acctUuid);
    if (listener != null) {
        listener.remoteSearchStarted(folderName);
    }
    List<Message> extraResults = new ArrayList<>();
    try {
        Store remoteStore = acct.getRemoteStore();
        LocalStore localStore = acct.getLocalStore();
        if (remoteStore == null || localStore == null) {
            throw new MessagingException("Could not get store");
        }
        Folder remoteFolder = remoteStore.getFolder(folderName);
        LocalFolder localFolder = localStore.getFolder(folderName);
        if (remoteFolder == null || localFolder == null) {
            throw new MessagingException("Folder not found");
        }
        List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags);
        Timber.i("Remote search got %d results", messages.size());
        // There's no need to fetch messages already completely downloaded
        List<Message> remoteMessages = localFolder.extractNewMessages(messages);
        messages.clear();
        if (listener != null) {
            listener.remoteSearchServerQueryComplete(folderName, remoteMessages.size(), acct.getRemoteSearchNumResults());
        }
        Collections.sort(remoteMessages, new UidReverseComparator());
        int resultLimit = acct.getRemoteSearchNumResults();
        if (resultLimit > 0 && remoteMessages.size() > resultLimit) {
            extraResults = remoteMessages.subList(resultLimit, remoteMessages.size());
            remoteMessages = remoteMessages.subList(0, resultLimit);
        }
        loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener);
    } catch (Exception e) {
        if (Thread.currentThread().isInterrupted()) {
            Timber.i(e, "Caught exception on aborted remote search; safe to ignore.");
        } else {
            Timber.e(e, "Could not complete remote search");
            if (listener != null) {
                listener.remoteSearchFailed(null, e.getMessage());
            }
            addErrorMessage(acct, null, e);
        }
    } finally {
        if (listener != null) {
            listener.remoteSearchFinished(folderName, 0, acct.getRemoteSearchNumResults(), extraResults);
        }
    }
}
Also used : LocalFolder(com.fsck.k9.mailstore.LocalFolder) SearchAccount(com.fsck.k9.search.SearchAccount) Account(com.fsck.k9.Account) LocalMessage(com.fsck.k9.mailstore.LocalMessage) MimeMessage(com.fsck.k9.mail.internet.MimeMessage) Message(com.fsck.k9.mail.Message) MessagingException(com.fsck.k9.mail.MessagingException) ArrayList(java.util.ArrayList) LocalStore(com.fsck.k9.mailstore.LocalStore) Store(com.fsck.k9.mail.Store) Pop3Store(com.fsck.k9.mail.store.pop3.Pop3Store) LocalStore(com.fsck.k9.mailstore.LocalStore) Folder(com.fsck.k9.mail.Folder) LocalFolder(com.fsck.k9.mailstore.LocalFolder) SuppressLint(android.annotation.SuppressLint) CertificateValidationException(com.fsck.k9.mail.CertificateValidationException) UnavailableStorageException(com.fsck.k9.mailstore.UnavailableStorageException) IOException(java.io.IOException) MessagingException(com.fsck.k9.mail.MessagingException) AuthenticationFailedException(com.fsck.k9.mail.AuthenticationFailedException) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 30 with VisibleForTesting

use of android.support.annotation.VisibleForTesting in project k-9 by k9mail.

the class MessageViewInfoExtractor method extractTextFromViewables.

/**
     * Extract the viewable textual parts of a message and return the rest as attachments.
     *
     * @return A {@link ViewableExtractedText} instance containing the textual parts of the message as
     *         plain text and HTML, and a list of message parts considered attachments.
     *
     * @throws com.fsck.k9.mail.MessagingException
     *          In case of an error.
     */
@VisibleForTesting
ViewableExtractedText extractTextFromViewables(List<Viewable> viewables) throws MessagingException {
    try {
        // Collect all viewable parts
        /*
             * Convert the tree of viewable parts into text and HTML
             */
        // Used to suppress the divider for the first viewable part
        boolean hideDivider = true;
        StringBuilder text = new StringBuilder();
        StringBuilder html = new StringBuilder();
        for (Viewable viewable : viewables) {
            if (viewable instanceof Textual) {
                // This is either a text/plain or text/html part. Fill the variables 'text' and
                // 'html', converting between plain text and HTML as necessary.
                text.append(buildText(viewable, !hideDivider));
                html.append(buildHtml(viewable, !hideDivider));
                hideDivider = false;
            } else if (viewable instanceof MessageHeader) {
                MessageHeader header = (MessageHeader) viewable;
                Part containerPart = header.getContainerPart();
                Message innerMessage = header.getMessage();
                addTextDivider(text, containerPart, !hideDivider);
                addMessageHeaderText(text, innerMessage);
                addHtmlDivider(html, containerPart, !hideDivider);
                addMessageHeaderHtml(html, innerMessage);
                hideDivider = true;
            } else if (viewable instanceof Alternative) {
                // Handle multipart/alternative contents
                Alternative alternative = (Alternative) viewable;
                /*
                     * We made sure at least one of text/plain or text/html is present when
                     * creating the Alternative object. If one part is not present we convert the
                     * other one to make sure 'text' and 'html' always contain the same text.
                     */
                List<Viewable> textAlternative = alternative.getText().isEmpty() ? alternative.getHtml() : alternative.getText();
                List<Viewable> htmlAlternative = alternative.getHtml().isEmpty() ? alternative.getText() : alternative.getHtml();
                // Fill the 'text' variable
                boolean divider = !hideDivider;
                for (Viewable textViewable : textAlternative) {
                    text.append(buildText(textViewable, divider));
                    divider = true;
                }
                // Fill the 'html' variable
                divider = !hideDivider;
                for (Viewable htmlViewable : htmlAlternative) {
                    html.append(buildHtml(htmlViewable, divider));
                    divider = true;
                }
                hideDivider = false;
            }
        }
        String content = HtmlConverter.wrapMessageContent(html);
        String sanitizedHtml = htmlSanitizer.sanitize(content);
        return new ViewableExtractedText(text.toString(), sanitizedHtml);
    } catch (Exception e) {
        throw new MessagingException("Couldn't extract viewable parts", e);
    }
}
Also used : Alternative(com.fsck.k9.mail.internet.Viewable.Alternative) Message(com.fsck.k9.mail.Message) Textual(com.fsck.k9.mail.internet.Viewable.Textual) MessagingException(com.fsck.k9.mail.MessagingException) MessagingException(com.fsck.k9.mail.MessagingException) Part(com.fsck.k9.mail.Part) Viewable(com.fsck.k9.mail.internet.Viewable) MessageHeader(com.fsck.k9.mail.internet.Viewable.MessageHeader) VisibleForTesting(android.support.annotation.VisibleForTesting)

Aggregations

VisibleForTesting (android.support.annotation.VisibleForTesting)63 File (java.io.File)24 FileNotFoundException (java.io.FileNotFoundException)15 Intent (android.content.Intent)11 IOException (java.io.IOException)11 MessagingException (com.fsck.k9.mail.MessagingException)8 ArrayList (java.util.ArrayList)8 AuthenticationFailedException (com.fsck.k9.mail.AuthenticationFailedException)6 CertificateValidationException (com.fsck.k9.mail.CertificateValidationException)6 UnavailableStorageException (com.fsck.k9.mailstore.UnavailableStorageException)6 Shared.getQuantityString (com.android.documentsui.Shared.getQuantityString)5 RootInfo (com.android.documentsui.model.RootInfo)5 LocalFolder (com.fsck.k9.mailstore.LocalFolder)5 LocalStore (com.fsck.k9.mailstore.LocalStore)5 HashMap (java.util.HashMap)5 SuppressLint (android.annotation.SuppressLint)4 LocalMessage (com.fsck.k9.mailstore.LocalMessage)4 Bundle (android.os.Bundle)3 Nullable (android.support.annotation.Nullable)3 Folder (com.fsck.k9.mail.Folder)3