Search in sources :

Example 6 with BoxException

use of com.box.androidsdk.content.BoxException in project box-android-sdk by box.

the class BoxRequestBatch method onSend.

@Override
public BoxResponseBatch onSend() throws BoxException {
    BoxResponseBatch responses = new BoxResponseBatch();
    if (mExecutor != null) {
        ArrayList<BoxFutureTask<BoxObject>> tasks = new ArrayList<BoxFutureTask<BoxObject>>();
        for (BoxRequest req : mRequests) {
            BoxFutureTask task = req.toTask();
            mExecutor.submit(task);
            tasks.add(task);
        }
        for (BoxFutureTask<BoxObject> task : tasks) {
            try {
                BoxResponse<BoxObject> response = task.get();
                responses.addResponse(response);
            } catch (InterruptedException e) {
                throw new BoxException(e.getMessage(), e);
            } catch (ExecutionException e) {
                throw new BoxException(e.getMessage(), e);
            }
        }
    } else {
        for (BoxRequest req : mRequests) {
            BoxObject value = null;
            Exception ex = null;
            try {
                value = req.send();
            } catch (Exception e) {
                ex = e;
            }
            BoxResponse<BoxObject> response = new BoxResponse<BoxObject>(value, ex, req);
            responses.addResponse(response);
        }
    }
    return responses;
}
Also used : BoxException(com.box.androidsdk.content.BoxException) ArrayList(java.util.ArrayList) BoxFutureTask(com.box.androidsdk.content.BoxFutureTask) ExecutionException(java.util.concurrent.ExecutionException) BoxException(com.box.androidsdk.content.BoxException) BoxObject(com.box.androidsdk.content.models.BoxObject) ExecutionException(java.util.concurrent.ExecutionException)

Example 7 with BoxException

use of com.box.androidsdk.content.BoxException in project box-android-sdk by box.

the class RealTimeServerConnection method connect.

/**
     * Returns a message once a change has been detected or error occurs. Otherwise this method will continue reconnecting.
     * @return A BoxSimpleMessage with a simple message indicating a change in the user's account.
     */
public BoxSimpleMessage connect() {
    mRetries = 0;
    try {
        BoxIteratorRealTimeServers servers = (BoxIteratorRealTimeServers) mRequest.send();
        mBoxRealTimeServer = servers.get(0);
    } catch (BoxException e) {
        mChangeListener.onException(e, this);
        return null;
    }
    BoxRequestsEvent.LongPollMessageRequest messageRequest = new BoxRequestsEvent.LongPollMessageRequest(mBoxRealTimeServer.getUrl(), mSession);
    messageRequest.setTimeOut(mBoxRealTimeServer.getFieldRetryTimeout().intValue() * 1000);
    boolean shouldRetry = true;
    do {
        BoxFutureTask<BoxSimpleMessage> task = null;
        try {
            task = messageRequest.toTask().addOnCompletedListener(this);
            mExecutor.submit(task);
            BoxResponse<BoxSimpleMessage> response = task.get(mBoxRealTimeServer.getFieldRetryTimeout().intValue(), TimeUnit.SECONDS);
            if (response.isSuccess() && !response.getResult().getMessage().equals(BoxSimpleMessage.MESSAGE_RECONNECT)) {
                return response.getResult();
            }
        } catch (TimeoutException e) {
            if (task != null) {
                try {
                    // if the timeout is coming from the task then cancel the task (as httpurlconnection timeout is unreliable).
                    task.cancel(true);
                } catch (CancellationException e1) {
                }
            }
        } catch (InterruptedException e) {
            mChangeListener.onException(e, this);
        } catch (ExecutionException e) {
            mChangeListener.onException(e, this);
        }
        mRetries++;
        if (mBoxRealTimeServer.getMaxRetries() < mRetries) {
            shouldRetry = false;
        }
    } while (shouldRetry);
    mChangeListener.onException(new BoxException.MaxAttemptsExceeded("Max retries exceeded, ", mRetries), this);
    return null;
}
Also used : BoxException(com.box.androidsdk.content.BoxException) BoxRequestsEvent(com.box.androidsdk.content.requests.BoxRequestsEvent) BoxIteratorRealTimeServers(com.box.androidsdk.content.models.BoxIteratorRealTimeServers) BoxSimpleMessage(com.box.androidsdk.content.models.BoxSimpleMessage) CancellationException(java.util.concurrent.CancellationException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 8 with BoxException

use of com.box.androidsdk.content.BoxException in project box-android-sdk by box.

the class BoxRequestMultipart method writeBody.

protected void writeBody(HttpURLConnection connection, ProgressListener listener) throws BoxException {
    try {
        connection.setChunkedStreamingMode(0);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        this.outputStream = connection.getOutputStream();
        for (Map.Entry<String, String> entry : this.fields.entrySet()) {
            this.writePartHeader(new String[][] { { "name", entry.getKey() } });
            this.writeOutput(entry.getValue());
        }
        this.writePartHeader(new String[][] { { "name", "filename" }, { "filename", this.filename } }, "application/octet-stream");
        OutputStream fileContentsOutputStream = this.outputStream;
        if (listener != null) {
            fileContentsOutputStream = new ProgressOutputStream(this.outputStream, listener, this.fileSize);
        }
        byte[] buffer = new byte[BUFFER_SIZE];
        int n = this.inputStream.read(buffer);
        while (n != -1) {
            fileContentsOutputStream.write(buffer, 0, n);
            n = this.inputStream.read(buffer);
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            this.loggedRequest.append("<File Contents Omitted>");
        }
        this.writeBoundary();
        this.writeOutput("--");
    } catch (IOException e) {
        throw new BoxException("Couldn't connect to the Box API due to a network error.", e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (Exception e) {
            }
        }
    }
}
Also used : BoxException(com.box.androidsdk.content.BoxException) OutputStream(java.io.OutputStream) ProgressOutputStream(com.box.androidsdk.content.utils.ProgressOutputStream) ProgressOutputStream(com.box.androidsdk.content.utils.ProgressOutputStream) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException) BoxException(com.box.androidsdk.content.BoxException)

Example 9 with BoxException

use of com.box.androidsdk.content.BoxException in project box-android-sdk by box.

the class BoxAuthentication method refresh.

/**
     * Refresh the OAuth in the given BoxSession. This method is called when OAuth token expires.
     * @param session a box session with all the necessary information to authenticate the user for the first time.
     * @return a future task allowing monitoring of the api call.
     * @throws BoxException thrown if there are any errors in refreshing this session.
     */
public synchronized FutureTask<BoxAuthenticationInfo> refresh(BoxSession session) throws BoxException {
    BoxUser user = session.getUser();
    if (user == null) {
        return doRefresh(session, session.getAuthInfo());
    }
    // Fetch auth info map from storage if not present.
    getAuthInfoMap(session.getApplicationContext());
    BoxAuthenticationInfo info = mCurrentAccessInfo.get(user.getId());
    if (info == null) {
        // session has info that we do not. ? is there any other situation we want to update our info based on session info? we can do checks against
        // refresh time.
        mCurrentAccessInfo.put(user.getId(), session.getAuthInfo());
        info = mCurrentAccessInfo.get(user.getId());
    }
    // No need to refresh if we have already refreshed within 15 seconds or have a newer access token already.
    if (session.getAuthInfo().accessToken() == null || (!session.getAuthInfo().accessToken().equals(info.accessToken()) && info.getRefreshTime() != null && System.currentTimeMillis() - info.getRefreshTime() < 15000)) {
        final BoxAuthenticationInfo latestInfo = info;
        // this session is probably using old information. Give it our information.
        BoxAuthenticationInfo.cloneInfo(session.getAuthInfo(), info);
        FutureTask task = new FutureTask<BoxAuthenticationInfo>(new Callable<BoxAuthenticationInfo>() {

            @Override
            public BoxAuthenticationInfo call() throws Exception {
                return latestInfo;
            }
        });
        AUTH_EXECUTOR.execute(task);
        return task;
    }
    FutureTask task = mRefreshingTasks.get(user.getId());
    if (task != null && !(task.isCancelled() || task.isDone())) {
        // We already have a refreshing task for this user. No need to do anything.
        return task;
    }
    // create the task to do the refresh and put it in mRefreshingTasks and execute it.
    return doRefresh(session, info);
}
Also used : FutureTask(java.util.concurrent.FutureTask) BoxFutureTask(com.box.androidsdk.content.BoxFutureTask) BoxUser(com.box.androidsdk.content.models.BoxUser) BoxException(com.box.androidsdk.content.BoxException)

Example 10 with BoxException

use of com.box.androidsdk.content.BoxException in project box-android-sdk by box.

the class BoxAuthentication method doRefresh.

private FutureTask<BoxAuthenticationInfo> doRefresh(final BoxSession session, final BoxAuthenticationInfo info) throws BoxException {
    final boolean userUnknown = (info.getUser() == null && session.getUser() == null);
    final String taskKey = SdkUtils.isBlank(session.getUserId()) && userUnknown ? info.accessToken() : session.getUserId();
    final String userId = (info.getUser() != null) ? info.getUser().getId() : session.getUserId();
    FutureTask<BoxAuthenticationInfo> task = new FutureTask<BoxAuthenticationInfo>(new Callable<BoxAuthenticationInfo>() {

        @Override
        public BoxAuthenticationInfo call() throws Exception {
            BoxAuthenticationInfo refreshInfo = null;
            if (session.getRefreshProvider() != null) {
                try {
                    refreshInfo = session.getRefreshProvider().refreshAuthenticationInfo(info);
                } catch (BoxException e) {
                    mRefreshingTasks.remove(taskKey);
                    throw handleRefreshException(session, e, info, userId);
                }
            } else if (mRefreshProvider != null) {
                try {
                    refreshInfo = mRefreshProvider.refreshAuthenticationInfo(info);
                } catch (BoxException e) {
                    mRefreshingTasks.remove(taskKey);
                    throw handleRefreshException(session, e, info, userId);
                }
            } else {
                String refreshToken = info.refreshToken() != null ? info.refreshToken() : "";
                String clientId = session.getClientId() != null ? session.getClientId() : BoxConfig.CLIENT_ID;
                String clientSecret = session.getClientSecret() != null ? session.getClientSecret() : BoxConfig.CLIENT_SECRET;
                if (SdkUtils.isBlank(clientId) || SdkUtils.isBlank(clientSecret)) {
                    BoxException badRequest = new BoxException("client id or secret not specified", 400, "{\"error\": \"bad_request\",\n" + "  \"error_description\": \"client id or secret not specified\"}", null);
                    throw handleRefreshException(session, badRequest, info, userId);
                }
                BoxApiAuthentication.BoxRefreshAuthRequest request = new BoxApiAuthentication(session).refreshOAuth(refreshToken, clientId, clientSecret);
                try {
                    refreshInfo = request.send();
                } catch (BoxException e) {
                    mRefreshingTasks.remove(taskKey);
                    throw handleRefreshException(session, e, info, userId);
                }
            }
            if (refreshInfo != null) {
                refreshInfo.setRefreshTime(System.currentTimeMillis());
            }
            BoxAuthenticationInfo.cloneInfo(session.getAuthInfo(), refreshInfo);
            // if we using a custom refresh provider ensure we check the user, otherwise do this only if we don't know who the user is.
            if (userUnknown || session.getRefreshProvider() != null || mRefreshProvider != null) {
                BoxApiUser userApi = new BoxApiUser(session);
                info.setUser(userApi.getCurrentUserInfoRequest().setFields(BoxUser.ALL_FIELDS).send());
            }
            getAuthInfoMap(session.getApplicationContext()).put(info.getUser().getId(), refreshInfo);
            getAuthStorage().storeAuthInfoMap(mCurrentAccessInfo, session.getApplicationContext());
            // call notifyListeners() with results.
            for (WeakReference<AuthListener> reference : mListeners) {
                AuthListener rc = reference.get();
                if (rc != null) {
                    rc.onRefreshed(refreshInfo);
                }
            }
            if (!session.getUserId().equals(info.getUser().getId())) {
                session.onAuthFailure(info, new BoxException("Session User Id has changed!"));
            }
            mRefreshingTasks.remove(taskKey);
            return info;
        }
    });
    mRefreshingTasks.put(taskKey, task);
    AUTH_EXECUTOR.execute(task);
    return task;
}
Also used : BoxException(com.box.androidsdk.content.BoxException) BoxException(com.box.androidsdk.content.BoxException) FutureTask(java.util.concurrent.FutureTask) BoxFutureTask(com.box.androidsdk.content.BoxFutureTask) BoxApiUser(com.box.androidsdk.content.BoxApiUser) WeakReference(java.lang.ref.WeakReference)

Aggregations

BoxException (com.box.androidsdk.content.BoxException)14 IOException (java.io.IOException)8 BoxFutureTask (com.box.androidsdk.content.BoxFutureTask)4 ExecutionException (java.util.concurrent.ExecutionException)4 InputStream (java.io.InputStream)3 BoxError (com.box.androidsdk.content.models.BoxError)2 ProgressInputStream (com.box.androidsdk.content.utils.ProgressInputStream)2 WeakReference (java.lang.ref.WeakReference)2 FutureTask (java.util.concurrent.FutureTask)2 GZIPInputStream (java.util.zip.GZIPInputStream)2 BoxApiUser (com.box.androidsdk.content.BoxApiUser)1 AuthFailure (com.box.androidsdk.content.auth.OAuthWebView.AuthFailure)1 BoxDownload (com.box.androidsdk.content.models.BoxDownload)1 BoxEntity (com.box.androidsdk.content.models.BoxEntity)1 BoxFile (com.box.androidsdk.content.models.BoxFile)1 BoxIteratorRealTimeServers (com.box.androidsdk.content.models.BoxIteratorRealTimeServers)1 BoxObject (com.box.androidsdk.content.models.BoxObject)1 BoxSimpleMessage (com.box.androidsdk.content.models.BoxSimpleMessage)1 BoxUser (com.box.androidsdk.content.models.BoxUser)1 BoxRequestsEvent (com.box.androidsdk.content.requests.BoxRequestsEvent)1