Search in sources :

Example 1 with AsyncHttpResponseHandler

use of com.loopj.android.http.AsyncHttpResponseHandler in project xabber-android by redsolution.

the class HttpFileUploadManager method uploadFile.

public void uploadFile(final String account, final String user, final String filePath) {
    final String uploadServerUrl = uploadServers.get(account);
    if (uploadServerUrl == null) {
        return;
    }
    final File file = new File(filePath);
    final Request httpFileUpload = new Request();
    httpFileUpload.setFilename(file.getName());
    httpFileUpload.setSize(String.valueOf(file.length()));
    httpFileUpload.setTo(uploadServerUrl);
    try {
        ConnectionManager.getInstance().sendRequest(account, httpFileUpload, new OnResponseListener() {

            @Override
            public void onReceived(final String account, String packetId, IQ iq) {
                if (!httpFileUpload.getStanzaId().equals(packetId) || !(iq instanceof Slot)) {
                    return;
                }
                uploadFileToSlot(account, (Slot) iq);
            }

            private void uploadFileToSlot(final String account, final Slot slot) {
                AsyncHttpClient client = new AsyncHttpClient();
                client.setLoggingEnabled(SettingsManager.debugLog());
                client.setResponseTimeout(60 * 1000);
                FileEntity fileEntity = new FileEntity(file, ContentType.DEFAULT_BINARY);
                LogManager.i(this, "fileEntity.getContentLength() " + fileEntity.getContentLength());
                client.put(Application.getInstance(), slot.getPutUrl(), fileEntity, CONTENT_TYPE, new AsyncHttpResponseHandler() {

                    MessageItem fileMessage;

                    @Override
                    public void onStart() {
                        super.onStart();
                        LogManager.i(this, "uploadFileToSlot onStart");
                        fileMessage = MessageManager.getInstance().createFileMessage(account, user, file);
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        LogManager.i(this, "uploadFileToSlot onSuccess " + i);
                        MessageManager.getInstance().replaceMessage(account, user, fileMessage, slot.getGetUrl());
                        if (FileManager.fileIsImage(file)) {
                            saveImageToCache(slot.getGetUrl(), file);
                        }
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        LogManager.i(this, "uploadFileToSlot onFailure " + i);
                        MessageManager.getInstance().updateMessageWithError(account, user, fileMessage, file.getName());
                    }

                    @Override
                    public void onRetry(int retryNo) {
                        super.onRetry(retryNo);
                        LogManager.i(this, "uploadFileToSlot onRetry " + retryNo);
                    }

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        LogManager.i(this, "uploadFileToSlot onCancel");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        LogManager.i(this, "uploadFileToSlot onFinish");
                    }
                });
            }

            @Override
            public void onError(String account, String packetId, IQ iq) {
                LogManager.i(this, "On HTTP file upload slot error");
                Application.getInstance().onError(R.string.http_file_upload_slot_error);
            }

            @Override
            public void onTimeout(String account, String packetId) {
            }

            @Override
            public void onDisconnect(String account, String packetId) {
            }
        });
    } catch (NetworkException e) {
        e.printStackTrace();
    }
}
Also used : MessageItem(com.xabber.android.data.message.MessageItem) FileEntity(cz.msebera.android.httpclient.entity.FileEntity) Request(com.xabber.xmpp.httpfileupload.Request) IQ(org.jivesoftware.smack.packet.IQ) AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) OnResponseListener(com.xabber.android.data.connection.OnResponseListener) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File) NetworkException(com.xabber.android.data.NetworkException) AsyncHttpClient(com.loopj.android.http.AsyncHttpClient)

Example 2 with AsyncHttpResponseHandler

use of com.loopj.android.http.AsyncHttpResponseHandler in project xabber-android by redsolution.

the class FileManager method downloadFile.

public void downloadFile(final MessageItem messageItem, final ProgressListener progressListener) {
    final String downloadUrl = messageItem.getText();
    if (startedDownloads.contains(downloadUrl)) {
        LogManager.i(FileManager.class, "Downloading of file " + downloadUrl + " already started");
        return;
    }
    LogManager.i(FileManager.class, "Downloading file " + downloadUrl);
    startedDownloads.add(downloadUrl);
    final AsyncHttpClient client = new AsyncHttpClient();
    client.setLoggingEnabled(SettingsManager.debugLog());
    client.setResponseTimeout(60 * 1000);
    client.get(downloadUrl, new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            super.onStart();
            LogManager.i(FileManager.class, "on download start");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final byte[] responseBody) {
            LogManager.i(FileManager.class, "on download onSuccess: " + statusCode);
            saveFile(responseBody, messageItem.getFile(), progressListener);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LogManager.i(FileManager.class, "on download onFailure: " + statusCode);
        }

        @Override
        public void onProgress(long bytesWritten, long totalSize) {
            if (progressListener != null) {
                progressListener.onProgress(bytesWritten, totalSize);
            }
        }

        @Override
        public void onFinish() {
            super.onFinish();
            startedDownloads.remove(downloadUrl);
        }
    });
}
Also used : Header(cz.msebera.android.httpclient.Header) AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) AsyncHttpClient(com.loopj.android.http.AsyncHttpClient)

Example 3 with AsyncHttpResponseHandler

use of com.loopj.android.http.AsyncHttpResponseHandler in project android-async-http by loopj.

the class AsyncBackgroundThreadSample method getResponseHandler.

@Override
public ResponseHandlerInterface getResponseHandler() {
    FutureTask<ResponseHandlerInterface> future = new FutureTask<>(new Callable<ResponseHandlerInterface>() {

        @Override
        public ResponseHandlerInterface call() throws Exception {
            Log.d(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread");
            return new AsyncHttpResponseHandler(Looper.getMainLooper()) {

                @Override
                public void onStart() {
                    clearOutputs();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    Log.d(LOG_TAG, String.format("onSuccess executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper()));
                    debugHeaders(LOG_TAG, headers);
                    debugStatusCode(LOG_TAG, statusCode);
                    debugResponse(LOG_TAG, new String(response));
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                    Log.d(LOG_TAG, String.format("onFailure executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper()));
                    debugHeaders(LOG_TAG, headers);
                    debugStatusCode(LOG_TAG, statusCode);
                    debugThrowable(LOG_TAG, e);
                    if (errorResponse != null) {
                        debugResponse(LOG_TAG, new String(errorResponse));
                    }
                }

                @Override
                public void onRetry(int retryNo) {
                    Toast.makeText(AsyncBackgroundThreadSample.this, String.format("Request is retried, retry no. %d", retryNo), Toast.LENGTH_SHORT).show();
                }
            };
        }
    });
    executor.execute(future);
    ResponseHandlerInterface responseHandler = null;
    try {
        responseHandler = future.get();
        Log.d(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseHandler;
}
Also used : AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) FutureTask(java.util.concurrent.FutureTask) Header(cz.msebera.android.httpclient.Header) ResponseHandlerInterface(com.loopj.android.http.ResponseHandlerInterface)

Example 4 with AsyncHttpResponseHandler

use of com.loopj.android.http.AsyncHttpResponseHandler in project sharelock-android by auth0.

the class LinkAPIClient method generateLinkForSecret.

public void generateLinkForSecret(Secret secret, Context context, final LinkCallback callback) {
    final Uri baseUri = this.baseUri;
    final String generateLinkURL = Uri.withAppendedPath(baseUri, "/create").toString();
    Map<String, Object> params = new HashMap<>();
    params.put("d", secret.getSecret());
    StringBuilder acl = new StringBuilder();
    for (String viewer : secret.getAllowedViewers()) {
        acl.append(viewer);
        acl.append(',');
    }
    acl.deleteCharAt(acl.length() - 1);
    params.put("a", acl.toString());
    final HttpEntity entity = entityBuilder.newEntityFrom(params);
    this.client.post(context, generateLinkURL, entity, "application/json", new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String pathSegment = new String(responseBody);
            if (pathSegment.startsWith("/")) {
                pathSegment = pathSegment.substring(1);
            }
            Uri linkUri = Uri.withAppendedPath(baseUri, pathSegment);
            callback.onSuccess(linkUri);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            callback.onError(error);
        }
    });
}
Also used : HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) Uri(android.net.Uri) Header(org.apache.http.Header)

Example 5 with AsyncHttpResponseHandler

use of com.loopj.android.http.AsyncHttpResponseHandler in project xabber-android by redsolution.

the class FileManager method getFileUrlSize.

private static void getFileUrlSize(final MessageItem messageItem) {
    LogManager.i(FileManager.class, "Requesting file size");
    AsyncHttpClient client = new AsyncHttpClient();
    client.head(messageItem.getText(), new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            for (Header header : headers) {
                if (header.getName().equals(HttpHeaders.CONTENT_LENGTH)) {
                    messageItem.setFileSize(Long.parseLong(header.getValue()));
                    MessageManager.getInstance().onChatChanged(messageItem.getChat().getAccount(), messageItem.getChat().getUser(), false);
                    break;
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        }
    });
}
Also used : Header(cz.msebera.android.httpclient.Header) AsyncHttpResponseHandler(com.loopj.android.http.AsyncHttpResponseHandler) AsyncHttpClient(com.loopj.android.http.AsyncHttpClient)

Aggregations

AsyncHttpResponseHandler (com.loopj.android.http.AsyncHttpResponseHandler)5 AsyncHttpClient (com.loopj.android.http.AsyncHttpClient)3 Header (cz.msebera.android.httpclient.Header)3 Uri (android.net.Uri)1 ResponseHandlerInterface (com.loopj.android.http.ResponseHandlerInterface)1 NetworkException (com.xabber.android.data.NetworkException)1 OnResponseListener (com.xabber.android.data.connection.OnResponseListener)1 MessageItem (com.xabber.android.data.message.MessageItem)1 Request (com.xabber.xmpp.httpfileupload.Request)1 Slot (com.xabber.xmpp.httpfileupload.Slot)1 FileEntity (cz.msebera.android.httpclient.entity.FileEntity)1 File (java.io.File)1 HashMap (java.util.HashMap)1 FutureTask (java.util.concurrent.FutureTask)1 Header (org.apache.http.Header)1 HttpEntity (org.apache.http.HttpEntity)1 IQ (org.jivesoftware.smack.packet.IQ)1