UploadActivity.java 32 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
package com.cnlive.demo.rdupload;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cnlive.lib.rdupload.network.HttpTask;
import com.ksyun.ks3.exception.Ks3Error;
import com.ksyun.ks3.model.PartETag;
import com.ksyun.ks3.model.acl.AccessControlList;
import com.ksyun.ks3.model.acl.CannedAccessControlList;
import com.ksyun.ks3.model.result.CompleteMultipartUploadResult;
import com.ksyun.ks3.model.result.InitiateMultipartUploadResult;
import com.ksyun.ks3.model.result.ListPartsResult;
import com.ksyun.ks3.services.AuthListener;
import com.ksyun.ks3.services.Ks3Client;
import com.ksyun.ks3.services.Ks3ClientConfiguration;
import com.ksyun.ks3.services.handler.CompleteMultipartUploadResponseHandler;
import com.ksyun.ks3.services.handler.InitiateMultipartUploadResponceHandler;
import com.ksyun.ks3.services.handler.ListPartsResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectResponseHandler;
import com.ksyun.ks3.services.handler.UploadPartResponceHandler;
import com.ksyun.ks3.services.request.CompleteMultipartUploadRequest;
import com.ksyun.ks3.services.request.InitiateMultipartUploadRequest;
import com.ksyun.ks3.services.request.ListPartsRequest;
import com.ksyun.ks3.services.request.PutObjectRequest;
import com.ksyun.ks3.services.request.UploadPartRequest;

/**
 * Upload相关API使用示例,Initiate Multipart Upload,Upload Part,List Parts, Complete
 * Multipart Upload等
 */
public class UploadActivity extends Activity implements OnItemClickListener {
    public static final long PART_SIZE = 5 * 1024 * 1024;
    private Ks3ClientConfiguration configuration;
    private Ks3Client client;
    private File currentDir;
    private ListView listView;
    private TextView currentDirTextView;
    private Map<String, List<UploadFile>> dataSource;
    private FileAdapter adapter;
    private final myHandler mHandler = new myHandler();
    private BucketInpuDialog bucketInpuDialog;
    private String mBucketName;

    private HttpTask httpTask;

    class ViewHolder {
        ImageView fileIcon;
        TextView fileNameTextView;
        LinearLayout fileSummaryLayout;
        TextView fileSizeTextView;
        TextView fileModiyTextView;
        LinearLayout uploadSummaryLayout;
        ProgressBar uploadProgressBar;
        TextView progressTextView;
        ImageView uploadBtn;
    }

    class FileAdapter extends BaseAdapter {
        private List<UploadFile> mUploadFiles;
        private LayoutInflater mInflater;

        FileAdapter(Context context, List<UploadFile> uploadFiles) {
            this.mUploadFiles = new ArrayList<UploadFile>();
            if (uploadFiles != null)
                this.mUploadFiles.addAll(uploadFiles);
            this.mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return mUploadFiles.size();
        }

        @Override
        public UploadFile getItem(int position) {
            return this.mUploadFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.upload_list_item,
                        parent, false);
                viewHolder = new ViewHolder();
                viewHolder.fileIcon = (ImageView) convertView
                        .findViewById(R.id.file_icon);
                viewHolder.fileNameTextView = (TextView) convertView
                        .findViewById(R.id.file_name);
                viewHolder.fileSummaryLayout = (LinearLayout) convertView
                        .findViewById(R.id.file_summary_layout);
                viewHolder.fileSizeTextView = (TextView) convertView
                        .findViewById(R.id.file_size);
                viewHolder.fileModiyTextView = (TextView) convertView
                        .findViewById(R.id.file_last_modiy);
                viewHolder.uploadSummaryLayout = (LinearLayout) convertView
                        .findViewById(R.id.progress_summary_layout);
                viewHolder.uploadProgressBar = (ProgressBar) convertView
                        .findViewById(R.id.upload_progress_bar);
                viewHolder.progressTextView = (TextView) convertView
                        .findViewById(R.id.upload_progress_txt);
                viewHolder.uploadBtn = (ImageView) convertView
                        .findViewById(R.id.upload_btn);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.fileIcon
                    .setImageDrawable(mUploadFiles.get(position).icon);
            viewHolder.fileNameTextView.setText(mUploadFiles.get(position).file
                    .getName());

            if (!mUploadFiles.get(position).file.isDirectory()) {
                viewHolder.fileSizeTextView.setVisibility(View.VISIBLE);
                long size = mUploadFiles.get(position).file.length();
                String sizeStr = "unkown-size";

                if (size >= 1024 * 1024) {
                    sizeStr = ((int) (size / 1024 / 1024) * 100) / 100 + "MB";
                } else {
                    sizeStr = (mUploadFiles.get(position).file.length() / 1024)
                            + "kb";
                }
                viewHolder.fileSizeTextView.setText(sizeStr);
                String modiyStr = DemoUtils.formatDate(mUploadFiles
                        .get(position).file.lastModified());
                viewHolder.fileModiyTextView.setText(modiyStr);
                if (mUploadFiles.get(position).status > UploadFile.STATUS_NOT_START) {
                    viewHolder.uploadSummaryLayout.setVisibility(View.VISIBLE);
                    viewHolder.uploadProgressBar.setProgress(mUploadFiles
                            .get(position).progress);
                    viewHolder.fileSummaryLayout.setVisibility(View.GONE);
                    viewHolder.uploadBtn.setVisibility(View.GONE);
                    switch (mUploadFiles.get(position).status) {
                        case UploadFile.STATUS_STARTED:
                            viewHolder.progressTextView.setText("准备上传");
                            break;
                        case UploadFile.STATUS_INIT:
                            viewHolder.progressTextView.setText("初始化完成");
                            break;
                        case UploadFile.STATUS_UPLOADPART:
                            viewHolder.progressTextView.setText("分块上传.."
                                    + mUploadFiles.get(position).progress + "%");
                            break;
                        case UploadFile.STATUS_LISTING:
                            viewHolder.progressTextView.setText("获取上传的快..");
                            break;
                        case UploadFile.STATUS_COMPLETE:
                            viewHolder.progressTextView.setText("合并完成");
                            break;
                        case UploadFile.STATUS_UPLOADING:
                            viewHolder.progressTextView.setText(mUploadFiles
                                    .get(position).progress + "%");
                            break;
                        case UploadFile.STATUS_FINISH:
                            viewHolder.progressTextView.setText("完成上传");
                            break;
                        case UploadFile.STATUS_FAIL:
                            viewHolder.progressTextView.setText("上传失败");
                            break;

                        case UploadFile.STATUS_INIT_FAIL:
                            viewHolder.progressTextView.setText("上传失败");
                            break;
                        case UploadFile.STATUS_UPLOADPART_FAIL:
                            viewHolder.progressTextView.setText("分块上传失败");
                            break;
                        case UploadFile.STATUS_LISTING_FAIL:
                            viewHolder.progressTextView.setText("获取块失败");
                            break;
                        case UploadFile.STATUS_COMPLETE_FAIL:
                            viewHolder.progressTextView.setText("文件合并失败");
                            break;
                    }
                } else {
                    viewHolder.fileSummaryLayout.setVisibility(View.VISIBLE);
                    viewHolder.uploadBtn.setVisibility(View.VISIBLE);
                    viewHolder.uploadSummaryLayout.setVisibility(View.GONE);
                }
            } else {
                viewHolder.fileSummaryLayout.setVisibility(View.GONE);
                viewHolder.uploadSummaryLayout.setVisibility(View.GONE);
                viewHolder.uploadBtn.setVisibility(View.GONE);
            }

            return convertView;
        }

        public void fillDatas() {
            this.mUploadFiles.clear();
            this.mUploadFiles.addAll(dataSource.get(currentDir.getPath()));
            this.notifyDataSetChanged();
        }

        public void updateCurrent() {
            this.notifyDataSetChanged();
        }
    }

    class UploadFile implements Serializable {
        private static final long serialVersionUID = 1L;
        static final int STATUS_NOT_START = 0;
        static final int STATUS_STARTED = 1;
        static final int STATUS_UPLOADING = 2;
        static final int STATUS_INIT = 3;
        static final int STATUS_UPLOADPART = 4;
        static final int STATUS_LISTING = 5;
        static final int STATUS_COMPLETE = 6;
        static final int STATUS_FINISH = 7;
        static final int STATUS_FAIL = 8;
        static final int STATUS_INIT_FAIL = 9;
        static final int STATUS_UPLOADPART_FAIL = 10;
        static final int STATUS_LISTING_FAIL = 11;
        static final int STATUS_COMPLETE_FAIL = 12;
        Drawable icon;
        File file;
        int progress;
        int status;

        @Override
        public String toString() {
            return file.getName() + ",upload?" + status + ",progress:"
                    + progress;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        listView = (ListView) findViewById(R.id.files);
        currentDirTextView = (TextView) findViewById(R.id.current_dir_tv);
        currentDir = Environment.getExternalStorageDirectory();
        setUp();

    }

    private void setUp() {
        //初始化Ks3Client并做鉴权
        if (httpTask == null) httpTask = new HttpTask();
        configuration = Ks3ClientConfiguration.getDefaultConfiguration();
        client = new Ks3Client(new AuthListener() {
            @Override
            public String onCalculateAuth(String s, String s1, String s2, String s3, String s4, String s5) {
                return httpTask.requestTokenToAppServer(s, s1, s2, s3, s4, s5).getAuthorization();
            }
        }, this);
        client.setEndpoint("ks3-cn-beijing.ksyun.com");
        client.setConfiguration(configuration);


        // 输入框确获取Bucket之后,允许选择文件,开始Upload操作
        bucketInpuDialog = new BucketInpuDialog(UploadActivity.this);
        bucketInpuDialog.setOnBucketInputListener(new BucketInpuDialog.OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                mBucketName = name;
                dataSource = new HashMap<String, List<UploadFile>>();
                adapter = new FileAdapter(UploadActivity.this, null);
                listView.setOnItemClickListener(UploadActivity.this);
                listView.setAdapter(adapter);
                switchDir(Environment.getExternalStorageDirectory());
            }
        });
        bucketInpuDialog.show();
        client.setConfiguration(configuration);
    }

    private void switchDir(File dir) {
        if (dir == null || !dir.exists() || dir.isFile())
            throw new IllegalArgumentException("illegal dir");

        this.currentDir = dir;
        this.currentDirTextView.setText("当前目录:" + this.currentDir.getPath());
        List<UploadFile> uploadFiles = dataSource.get(dir.getPath());
        if (uploadFiles != null && uploadFiles.size() > 0) {
            adapter.fillDatas();
            return;
        }

        uploadFiles = new ArrayList<UploadFile>();
        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                UploadFile uploadFile = new UploadFile();
                uploadFile.status = UploadFile.STATUS_NOT_START;
                uploadFile.file = file;
                uploadFile.icon = DemoUtils.matchImage(this,
                        file.isDirectory(), file.getName());
                uploadFile.progress = 0;
                uploadFiles.add(uploadFile);
            }
        }
        dataSource.put(dir.getPath(), uploadFiles);
        adapter.fillDatas();
    }

    @Override
    public void onItemClick(AdapterView<?> adpterView, final View view,
                            final int position, long arg3) {
        final UploadFile item = adapter.getItem(position);
        if (item.file.isDirectory()) {
            switchDir(item.file);
        } else {
            if (item.status == UploadFile.STATUS_STARTED
                    || item.status == UploadFile.STATUS_UPLOADING
                    || item.status == UploadFile.STATUS_FINISH)
                return;
            // 上传操作
            doUpload(mBucketName, item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (currentDir.getPath().equalsIgnoreCase(
                    Environment.getExternalStorageDirectory().getPath())) {
                return super.onKeyDown(keyCode, event);
            } else {
                switchDir(currentDir.getParentFile());
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void doUpload(String bucketName, UploadFile item) {
        if (item.file == null)
            throw new IllegalArgumentException("file can not be null");
        // 根据指定的文件大小,选择用直接上传或者分块上传
        if (item.file.length() >= Constants.MULTI_UPLOAD_THREADHOLD)
            doMultipartUpload(bucketName, item);
        else
            doSingleUpload(bucketName, item);
    }

    // 上传文件
    private void doSingleUpload(final String bucketName, final UploadFile item) {
        final PutObjectRequest request = new PutObjectRequest(bucketName,
                item.file.getName(), item.file);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
//		Map<String,String> customParams = new HashMap<String, String>();
        //自定义参数必须以kss-开头
//		customParams.put("kss-location", "user_input_location");
//		customParams.put("kss-name", "user_input_name");
//		request.setCallBack("http://127.0.0.1:19091/kss/call_back", "objectKey=${key}&etag=${etag}&location=${kss-location}&name=${kss-name}", customParams);
        client.putObject(request, new PutObjectResponseHandler() {

            @Override
            public void onTaskProgress(double progress) {
                // if (progress > 50.0) {
                // request.abort();
                // }
                List<UploadFile> uploadFiles = dataSource.get(currentDir
                        .getPath());
                for (UploadFile file : uploadFiles) {
                    if (file.file.getPath().equalsIgnoreCase(
                            item.file.getPath())) {
                        file.status = UploadFile.STATUS_UPLOADING;
                        file.progress = (int) progress;
                        item.status = UploadFile.STATUS_UPLOADING;
                        item.progress = (int) progress;
                    }
                }
                mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
            }

            @Override
            public void onTaskSuccess(int statesCode, Header[] responceHeaders) {
                Log.d(com.ksyun.ks3.util.Constants.LOG_TAG, "success");
            }

            @Override
            public void onTaskStart() {
                List<UploadFile> uploadFiles = dataSource.get(currentDir
                        .getPath());
                for (UploadFile file : uploadFiles) {
                    if (file.file.getPath().equalsIgnoreCase(
                            item.file.getPath())) {
                        file.status = UploadFile.STATUS_STARTED;
                        file.progress = 0;
                        item.status = UploadFile.STATUS_STARTED;
                        item.progress = 0;
                    }
                }
                mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
            }

            @Override
            public void onTaskFinish() {
                List<UploadFile> uploadFiles = dataSource.get(currentDir
                        .getPath());
                for (UploadFile file : uploadFiles) {
                    if (file.file.getPath().equalsIgnoreCase(
                            item.file.getPath())) {
                        file.status = UploadFile.STATUS_FINISH;
                        file.progress = 100;
                        item.status = UploadFile.STATUS_FINISH;
                        file.progress = 100;
                    }
                }
                mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
            }

            @Override
            public void onTaskCancel() {
                Log.d(com.ksyun.ks3.util.Constants.LOG_TAG, "cancle ok");
            }

            @Override
            public void onTaskFailure(int statesCode, Ks3Error error,
                                      Header[] responceHeaders, String response,
                                      Throwable paramThrowable) {
                Log.d(com.ksyun.ks3.util.Constants.LOG_TAG,
                        paramThrowable.toString());
                Log.d(com.ksyun.ks3.util.Constants.LOG_TAG,
                        response);
                List<UploadFile> uploadFiles = dataSource.get(currentDir
                        .getPath());
                for (UploadFile file : uploadFiles) {
                    if (file.file.getPath().equalsIgnoreCase(
                            item.file.getPath())) {
                        file.status = UploadFile.STATUS_FAIL;
                        item.status = UploadFile.STATUS_FAIL;
                    }
                }
                mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);

            }
        });
    }

    // 分快上传
    private void doMultipartUpload(final String bucketName,
                                   final UploadFile item) {
        InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(
                bucketName, item.file.getName());
        initiateMultipartUpload(request, item);
    }

    private void initiateMultipartUpload(
            final InitiateMultipartUploadRequest request, final UploadFile item) {
        client.initiateMultipartUpload(request,
                new InitiateMultipartUploadResponceHandler() {
                    @Override
                    public void onSuccess(int statesCode,
                                          Header[] responceHeaders,
                                          InitiateMultipartUploadResult result) {
                        List<UploadFile> uploadFiles = dataSource
                                .get(currentDir.getPath());
                        for (UploadFile file : uploadFiles) {
                            if (file.file.getPath().equalsIgnoreCase(
                                    item.file.getPath())) {
                                file.status = UploadFile.STATUS_INIT;
                                item.status = UploadFile.STATUS_INIT;
                            }
                        }
                        mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);

                        beginMultiUpload(result, item);
                    }

                    @Override
                    public void onFailure(int statesCode, Ks3Error error,
                                          Header[] responceHeaders, String response,
                                          Throwable paramThrowable) {
                        List<UploadFile> uploadFiles = dataSource
                                .get(currentDir.getPath());
                        for (UploadFile file : uploadFiles) {
                            if (file.file.getPath().equalsIgnoreCase(
                                    item.file.getPath())) {
                                file.status = UploadFile.STATUS_INIT_FAIL;
                                item.status = UploadFile.STATUS_INIT_FAIL;
                            }
                        }
                        mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
                    }
                });
    }

    private void beginMultiUpload(InitiateMultipartUploadResult initResult,
                                  UploadFile item) {
        UploadPartRequestFactory localUploadPartRequestFactory = new UploadPartRequestFactory(
                initResult.getBucket(), initResult.getKey(),
                initResult.getUploadId(), item.file, PART_SIZE);
        Message message = mHandler.obtainMessage();
        message.what = UPLOAD_NEXT_PART;
        Bundle bundle = new Bundle();
        bundle.putSerializable("requestFactory", localUploadPartRequestFactory);
        bundle.putSerializable("uploadFile", item);
        message.setData(bundle);
        mHandler.sendMessage(message);
    }

    private void uploadpart(final UploadPartRequestFactory requestFactory,
                            final UploadFile item) {
        if (requestFactory.hasMoreRequests()) {
            final UploadPartRequest request = requestFactory
                    .getNextUploadPartRequest();
            client.uploadPart(request, new UploadPartResponceHandler() {
                double progressInFile = 0;

                @Override
                public void onTaskProgress(double progress) {
                    long uploadedInpart = (long) (progress / 100 * request.contentLength);
                    long uploadedInFile = uploadedInpart
                            + requestFactory.getUploadedSize();
                    progressInFile = Double
                            .valueOf(request.getFile().length() > 0 ? uploadedInFile
                                    * 1.0D
                                    / request.getFile().length()
                                    * 100.0D
                                    : -1.0D);

                    List<UploadFile> uploadFiles = dataSource.get(currentDir
                            .getPath());
                    for (UploadFile file : uploadFiles) {
                        if (file.file.getPath().equalsIgnoreCase(
                                item.file.getPath())) {
                            file.status = UploadFile.STATUS_UPLOADPART;
                            file.progress = (int) progressInFile;
                            item.status = UploadFile.STATUS_UPLOADPART;
                            file.progress = (int) progressInFile;
                        }
                    }
                    mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
                }

                @Override
                public void onSuccess(int statesCode, Header[] responceHeaders,
                                      PartETag result) {
                    Message message = mHandler.obtainMessage();
                    message.what = UPLOAD_NEXT_PART;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("requestFactory", requestFactory);
                    bundle.putSerializable("uploadFile", item);
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                }

                @Override
                public void onFailure(int statesCode, Ks3Error error,
                                      Header[] responceHeaders, String response,
                                      Throwable throwable) {
                    List<UploadFile> uploadFiles = dataSource.get(currentDir
                            .getPath());
                    for (UploadFile file : uploadFiles) {
                        if (file.file.getPath().equalsIgnoreCase(
                                item.file.getPath())) {
                            file.status = UploadFile.STATUS_UPLOADPART_FAIL;
                            file.progress = (int) progressInFile;
                            item.status = UploadFile.STATUS_UPLOADPART_FAIL;
                            file.progress = (int) progressInFile;
                        }
                    }
                    mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
                }
            });
        } else {
            Message message = mHandler.obtainMessage();
            message.what = UPLOAD_PART_FINISH;
            Bundle bundle = new Bundle();
            bundle.putSerializable("requestFactory", requestFactory);
            bundle.putSerializable("uploadFile", item);
            message.setData(bundle);
            mHandler.sendMessage(message);
        }
    }

    private void listParts(final ListPartsRequest request, final UploadFile item) {
        client.listParts(request, new ListPartsResponseHandler() {
            @Override
            public void onSuccess(int statesCode, Header[] responceHeaders,
                                  ListPartsResult result) {
                Message message = mHandler.obtainMessage();
                message.what = LIST_PART_FINISH;
                message.obj = result;
                Bundle bundle = new Bundle();
                bundle.putSerializable("uploadFile", item);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(int statesCode, Ks3Error error,
                                  Header[] responceHeaders, String response,
                                  Throwable paramThrowable) {
                List<UploadFile> uploadFiles = dataSource.get(currentDir
                        .getPath());
                for (UploadFile file : uploadFiles) {
                    if (file.file.getPath().equalsIgnoreCase(
                            item.file.getPath())) {
                        file.status = UploadFile.STATUS_LISTING_FAIL;
                        item.status = UploadFile.STATUS_LISTING_FAIL;
                    }
                }
                mHandler.sendEmptyMessage(UPDATE_SINGLE_UPLOAD_STATUS);
            }
        });
    }

    private void completeUploadPart(
            final CompleteMultipartUploadRequest request, final UploadFile item) {
        client.completeMultipartUpload(request,
                new CompleteMultipartUploadResponseHandler() {
                    @Override
                    public void onSuccess(int statesCode,
                                          Header[] responceHeaders,
                                          CompleteMultipartUploadResult result) {
                        List<UploadFile> uploadFiles = dataSource
                                .get(currentDir.getPath());
                        for (UploadFile file : uploadFiles) {
                            if (file.file.getPath().equalsIgnoreCase(
                                    item.file.getPath())) {
                                file.status = UploadFile.STATUS_COMPLETE;
                                item.status = UploadFile.STATUS_COMPLETE;
                            }
                        }
                        mHandler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onFailure(int statesCode, Ks3Error error,
                                          Header[] responceHeaders, String response,
                                          Throwable paramThrowable) {
                        List<UploadFile> uploadFiles = dataSource
                                .get(currentDir.getPath());
                        for (UploadFile file : uploadFiles) {
                            if (file.file.getPath().equalsIgnoreCase(
                                    item.file.getPath())) {
                                file.status = UploadFile.STATUS_COMPLETE_FAIL;
                                file.progress = 100;
                                item.status = UploadFile.STATUS_COMPLETE_FAIL;
                                item.progress = 100;
                            }
                        }
                        mHandler.sendEmptyMessage(0);
                    }
                });
    }

    private static final int UPDATE_SINGLE_UPLOAD_STATUS = 0;
    private static final int UPLOAD_NEXT_PART = 2;
    private static final int UPLOAD_PART_FINISH = 3;
    private static final int LIST_PART_FINISH = 4;

    @SuppressLint("HandlerLeak")
    class myHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            Bundle bundle;
            UploadFile item;
            UploadPartRequestFactory requestFactory;
            switch (what) {
                case UPDATE_SINGLE_UPLOAD_STATUS:
                    adapter.updateCurrent();
                    break;
                case UPLOAD_NEXT_PART:
                    bundle = msg.getData();
                    requestFactory = (UploadPartRequestFactory) bundle
                            .get("requestFactory");
                    item = (UploadFile) bundle.get("uploadFile");
                    uploadpart(requestFactory, item);
                    break;
                case UPLOAD_PART_FINISH:
                    bundle = msg.getData();
                    requestFactory = (UploadPartRequestFactory) bundle
                            .get("requestFactory");
                    item = (UploadFile) bundle.get("uploadFile");
                    ListPartsRequest listRequest = new ListPartsRequest(
                            requestFactory.getBucketName(),
                            requestFactory.getObjectKey(),
                            requestFactory.getUploadId());
                    listParts(listRequest, item);
                    break;
                case LIST_PART_FINISH:
                    ListPartsResult listResult = (ListPartsResult) msg.obj;
                    bundle = msg.getData();
                    item = (UploadFile) bundle.get("uploadFile");
                    CompleteMultipartUploadRequest comRequest = new CompleteMultipartUploadRequest(
                            listResult);
                    completeUploadPart(comRequest, item);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}