Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.koushikdutta.ion;
  
  import  android.app.ProgressDialog;
  import  android.graphics.Bitmap;
  import  android.net.Uri;
  import  android.os.Handler;
  import  android.os.Looper;
  import  android.text.TextUtils;
  import  android.util.Base64;
 import  android.util.Log;
 import  android.widget.ImageView;
 import  android.widget.ProgressBar;
 
 
 import  org.apache.http.NameValuePair;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;

Created by koush on 5/21/13.
 
     Ion ion;
     Handler handler = .;
     String uri;
 
     public IonRequestBuilder(ContextReference contextReferenceIon ion) {
         String alive = contextReference.isAlive();
         if (null != alive)
             Log.w("Ion""Building request with dead context: " + alive);
         this. = ion;
         this. = contextReference;
     }
 
     @Override
     public IonRequestBuilder load(String url) {
         return loadInternal(.url);
     }
    private IonRequestBuilder loadInternal(String methodString url) {
        this. = method;
        if (!TextUtils.isEmpty(url) && url.startsWith("/"))
            url = new File(url).toURI().toString();
        this. = url;
        return this;
    }
    boolean methodWasSet;
    @Override
    public IonRequestBuilder load(String methodString url) {
         = true;
        return loadInternal(methodurl);
    }
    private Headers getHeaders() {
        if ( == null) {
             = new Headers();
            AsyncHttpRequest.setDefaultHeaders( == null ? null : Uri.parse());
        }
        return ;
    }
    @Override
    public IonRequestBuilder userAgent(String userAgent) {
        if (TextUtils.isEmpty(userAgent))
            return this;
        return setHeader("User-Agent"userAgent);
    }
    @Override
    public IonRequestBuilder setHeader(String nameString value) {
        if (value == null)
            getHeaders().removeAll(name);
        else
            getHeaders().set(namevalue);
        return this;
    }
    @Override
    public IonRequestBuilder addHeader(String nameString value) {
        if (value != null)
            getHeaders().add(namevalue);
        return this;
    }
    @Override
    public IonRequestBuilder addHeaders(Map<StringList<String>> params) {
        if (params == null)
            return this;
        Headers headers = getHeaders();
        for (Map.Entry<StringList<String>> entryparams.entrySet()) {
            headers.addAll(entry.getKey(), entry.getValue());
        }
        return this;
    }
    boolean noCache;
    @Override
    public Builders.Any.B noCache() {
         = true;
        return setHeader("Cache-Control""no-cache");
    }
    Multimap query;
    @Override
    public IonRequestBuilder addQuery(String nameString value) {
        if (value == null)
            return this;
        if ( == null)
             = new Multimap();
        .add(namevalue);
        return this;
    }
    @Override
    public IonRequestBuilder addQueries(Map<StringList<String>> params) {
       if ( == null)
           = new Multimap();
       .putAll(params);
       return this;
    }
    @Override
    public IonRequestBuilder setTimeout(int timeoutMilliseconds) {
        this. = timeoutMilliseconds;
        return this;
    }
    @Override
    public IonRequestBuilder setHandler(Handler handler) {
        this. = handler;
        return this;
    }
    private <T> IonRequestBuilder setBody(AsyncHttpRequestBody<T> body) {
        if (!)
             = .;
        this. = body;
        return this;
    }
    @Override
    public IonRequestBuilder setJsonObjectBody(JsonObject jsonObject) {
        return setBody(new GsonBody<JsonObject>(.configure().getGson(), jsonObject));
    }
    @Override
    public IonRequestBuilder setJsonArrayBody(JsonArray jsonArray) {
        return setBody(new GsonBody<JsonArray>(.configure().getGson(), jsonArray));
    }
    @Override
    public IonRequestBuilder setStringBody(String string) {
        return setBody(new StringBody(string));
    }
    boolean followRedirect = true;
    @Override
    public IonRequestBuilder followRedirect(boolean follow) {
         = follow;
        return this;
    }
    private <T> void postExecute(final EmitterTransform<T> futurefinal Exception exfinal T value) {
        final Runnable runner = new Runnable() {
            @Override
            public void run() {
                // check if the context is still alive...
                String deadReason = .isAlive();
                if (deadReason != null) {
                    future.initialRequest.logd("context has died: " + deadReason);
                    future.cancelSilently();
                    return;
                }
                // unless we're invoked onto the handler/main/service thread, there's no frakking way to avoid a
                // race condition where the service or activity dies before this callback is invoked.
                if (ex != null)
                    future.setComplete(ex);
                else
                    future.setComplete(value);
            }
        };
        if ( == null)
            ..getServer().post(runner);
        else
            AsyncServer.post(runner);
    }
    private Uri prepareURI() {
        Uri uri;
        try {
            if ( != null) {
                Uri.Builder builder = Uri.parse(this.).buildUpon();
                for (String key.keySet()) {
                    for (String value.get(key)) {
                        builder = builder.appendQueryParameter(keyvalue);
                    }
                }
                uri = builder.build();
            }
            else {
                uri = Uri.parse(this.);
            }
        }
        catch (Exception e) {
            uri = null;
        }
        if (uri == null || uri.getScheme() == null)
            return null;
        return uri;
    }
    private AsyncHttpRequest prepareRequest(Uri uriAsyncHttpRequestBody wrappedBody) {
        request.setFollowRedirect();
        request.setBody(wrappedBody);
        request.setLogging(..);
        if ( != null)
            request.setLogging();
        request.enableProxy();
        request.setTimeout();
        request.logd("preparing request");
        return request;
    }
    static interface LoadRequestCallback {
        boolean loadRequest(AsyncHttpRequest request);
    }
    private <T> void getLoaderEmitter(final EmitterTransform<T> ret) {
        Uri uri = prepareURI();
        if (uri == null) {
            ret.setComplete(new Exception("Invalid URI"));
            return;
        }
        AsyncHttpRequestBody wrappedBody = ;
        if ( != null ||  != null ||  != null ||  != null) {
            wrappedBody = new RequestBodyUploadObserver(new ProgressCallback() {
                @Override
                public void onProgress(final long downloadedfinal long total) {
                    assert Thread.currentThread() != Looper.getMainLooper().getThread();
                    final int percent = (int)((float)downloaded / total * 100f);
                    if ( != null)
                        .setProgress(percent);
                    if ( != null)
                        .setProgress(percent);
                    if ( != null)
                        .onProgress(downloadedtotal);
                    if ( != null) {
                        AsyncServer.post(.new Runnable() {
                            @Override
                            public void run() {
                                if (ret.isCancelled() || ret.isDone())
                                    return;
                                .onProgress(downloadedtotal);
                            }
                        });
                    }
                }
            });
        }
        AsyncHttpRequest request = prepareRequest(uriwrappedBody);
        ret.initialRequest = request;
        resolveAndLoadRequest(requestret);
    }
    <T> void resolveAndLoadRequest(final AsyncHttpRequest requestfinal EmitterTransform<T> ret) {
        Future<AsyncHttpRequestresolved = resolveRequest(requestret);
        if (resolved != null) {
            resolved.setCallback(new FutureCallback<AsyncHttpRequest>() {
                @Override
                public void onCompleted(Exception efinal AsyncHttpRequest result) {
                    if (e != null) {
                        ret.setComplete(e);
                        return;
                    }
                    ret.finalRequest = result;
                    resolveAndLoadRequest(resultret);
                }
            });
            return;
        }
        if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
            AsyncServer.post(.new Runnable() {
                @Override
                public void run() {
                    invokeLoadRequest(requestret);
                }
            });
            return;
        }
        invokeLoadRequest(requestret);
    }
    <T> void invokeLoadRequest(final AsyncHttpRequest requestfinal EmitterTransform<T> ret) {
        if ( == null || .loadRequest(request))
            loadRequest(requestret);
    }
    <T> void loadRequest(AsyncHttpRequest requestfinal EmitterTransform<T> ret) {
        // now attempt to fetch it directly
        for (Loader loader.) {
            Future<DataEmitteremitter = loader.load(requestret);
            if (emitter != null) {
                request.logi("Using loader: " + loader);
                ret.setParent(emitter);
                return;
            }
        }
        ret.setComplete(new Exception("Unknown uri scheme"));
    }
    <T> Future<AsyncHttpRequestresolveRequest(AsyncHttpRequest requestfinal EmitterTransform<T> ret) {
        // first attempt to resolve the url
        for (Loader loader.) {
            Future<AsyncHttpRequestresolved = loader.resolve(.getContext(), request);
            if (resolved != null)
                return resolved;
        }
        return null;
    }
    // transforms a LoaderEmitter, which is a DataEmitter and all associated properties about the data source
    // into the final result.
    class EmitterTransform<T> extends TransformFuture<T, LoaderEmitterimplements ResponseFuture<T> {
        int loadedFrom;
        Runnable cancelCallback;
        HeadersResponse headers;
        DataEmitter emitter;
        public Response<T> getResponse(Exception e, T result) {
            Response<T> response = new Response<T>();
            response.headers = ;
            response.request = ;
            response.result = result;
            response.exception = e;
            return response;
        }
        @Override
        public Future<Response<T>> withResponse() {
            final SimpleFuture<Response<T>> ret = new SimpleFuture<Response<T>>();
            setCallback(new FutureCallback<T>() {
                @Override
                public void onCompleted(Exception e, T result) {
                    if ( != null) {
                        ret.setComplete(getResponse(eresult));
                        return;
                    }
                    ret.setComplete(enull);
                }
            });
            ret.setParent(this);
            return ret;
        }
        public int loadedFrom() {
            return ;
        }
        public EmitterTransform(Runnable cancelCallback) {
            this. = cancelCallback;
            .addFutureInFlight(this.getContext());
            if ( == null)
                return;
            for (WeakReference<Objectref) {
                Object group = ref.get();
                if (group != null)
                    .addFutureInFlight(thisgroup);
            }
        }
        @Override
        protected void cancelCleanup() {
            super.cancelCleanup();
            if ( != null)
                .close();
            if ( != null)
                .run();
        }
        @Override
        protected void error(Exception e) {
            // don't call superclass which calls setComplete... get onto handler thread.
            postExecute(thisenull);
        }
        @Override
        protected void transform(LoaderEmitter emitterthrows Exception {
            this. = emitter.getDataEmitter();
            this. = emitter.loadedFrom();
            this. = emitter.getHeaders();
            this. = emitter.getRequest();
            if ( != null) {
                final HeadersResponse headers = emitter.getHeaders();
                // what do we do on loaders that don't have headers? files, content://, etc.
                AsyncServer.post(new Runnable() {
                    @Override
                    public void run() {
                        .onHeaders(headers);
                    }
                });
            }
            // hook up data progress callbacks
            final long total = emitter.length();
            DataTrackingEmitter tracker;
            if (!(this. instanceof DataTrackingEmitter)) {
                tracker = new FilteredDataEmitter();
                tracker.setDataEmitter(this.);
            }
            else {
                tracker = (DataTrackingEmitter)this.;
            }
            this. = tracker;
            tracker.setDataTracker(new DataTracker() {
                int lastPercent;
                @Override
                public void onData(final int totalBytesRead) {
                    assert Thread.currentThread() != Looper.getMainLooper().getThread();
                    // if the requesting context dies during the transfer... cancel
                    String deadReason = .isAlive();
                    if (deadReason != null) {
                        .logd("context has died, cancelling");
                        cancelSilently();
                        return;
                    }
                    final int percent = (int)((float)totalBytesRead / total * 100f);
                    if (( != null ||  != null) && percent != ) {
                        AsyncServer.post(.new Runnable() {
                            @Override
                            public void run() {
                                if ( != null) {
                                    ProgressBar bar = .get();
                                    if (bar != null)
                                        bar.setProgress(percent);
                                }
                                if ( != null) {
                                    ProgressDialog dlg = .get();
                                    if (dlg != null)
                                        dlg.setProgress(percent);
                                }
                            }
                        });
                    }
                     = percent;
                    if ( != null)
                        .onProgress(totalBytesReadtotal);
                    if ( != null) {
                        AsyncServer.post(.new Runnable() {
                            @Override
                            public void run() {
                                if (isCancelled() || isDone())
                                    return;
                                .onProgress(totalBytesReadtotal);
                            }
                        });
                    }
                }
            });
        }
    }
    @Override
    public IonRequestBuilder progressBar(ProgressBar progressBar) {
        this. = new WeakReference<ProgressBar>(progressBar);
        return this;
    }
    @Override
    public IonRequestBuilder progressDialog(ProgressDialog progressDialog) {
        this. = new WeakReference<ProgressDialog>(progressDialog);
        return this;
    }
    WeakReference<ProgressBar> progressBar;
    WeakReference<ProgressDialog> progressDialog;
    @Override
    public IonRequestBuilder progress(ProgressCallback callback) {
         = callback;
        return this;
    }
    @Override
         = callback;
        return this;
    }
    <T> EmitterTransform<T> execute(final DataSink sinkfinal boolean closefinal T result) {
        return execute(sinkcloseresultnull);
    }
    <T> EmitterTransform<T> execute(final DataSink sinkfinal boolean closefinal T resultfinal Runnable cancel) {
        EmitterTransform<T> ret = new EmitterTransform<T>(cancel) {
            @Override
            protected void cleanup() {
                super.cleanup();
                if (close)
                    sink.end();
            }
            EmitterTransform<T> self = this;
            @Override
            protected void transform(LoaderEmitter emitterthrows Exception {
                super.transform(emitter);
                Util.pump(this.sinknew CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        postExecute(exresult);
                    }
                });
            }
        };
        getLoaderEmitter(ret);
        return ret;
    }
    <T> EmitterTransform<T> execute(final AsyncParser<T> parser) {
        return execute(parsernull);
    }
    <T> EmitterTransform<T> execute(final AsyncParser<T> parserRunnable cancel) {
        assert parser != null;
        EmitterTransform<T> ret = new EmitterTransform<T>(cancel) {
            EmitterTransform<T> self = this;
            @Override
            protected void transform(LoaderEmitter emitterthrows Exception {
                super.transform(emitter);
                parser.parse(this.).setCallback(new FutureCallback<T>() {
                    @Override
                    public void onCompleted(Exception e, T result) {
                        postExecute(eresult);
                    }
                });
            }
        };
        getLoaderEmitter(ret);
        return ret;
    }
        Uri uri = prepareURI();
        if (uri == null)
            return null;
        AsyncHttpRequest request = prepareRequest(urinull);
        for (Loader loader.) {
            Future<InputStreamret = loader.load(request);
            if (ret != null)
                return ret;
        }
        return null;
    }
    @Override
        return execute(new GsonObjectParser());
    }
    @Override
    public ResponseFuture<JsonArrayasJsonArray() {
        return execute(new GsonArrayParser());
    }
    @Override
    public ResponseFuture<JsonObjectasJsonObject(Charset charset) {
        return execute(new GsonObjectParser(charset));
    }
    @Override
    public ResponseFuture<JsonArrayasJsonArray(Charset charset) {
        return execute(new GsonArrayParser(charset));
    }
    @Override
    public ResponseFuture<StringasString() {
        return execute(new StringParser());
    }
    @Override
    public ResponseFuture<StringasString(Charset charset) {
        return execute(new StringParser(charset));
    }
    @Override
    public ResponseFuture<byte[]> asByteArray() {
        return execute(new AsyncParser<byte[]>() {
            @Override
            public Future<byte[]> parse(DataEmitter emitter) {
                return new ByteBufferListParser().parse(emitter)
                .then(new TransformFuture<byte[], ByteBufferList>() {
                    @Override
                    protected void transform(ByteBufferList resultthrows Exception {
                        setComplete(result.getAllByteArray());
                    }
                });
            }
            @Override
            public void write(DataSink sinkbyte[] valueCompletedCallback completed) {
                new ByteBufferListParser().write(sinknew ByteBufferList(value), completed);
            }
        });
    }
    @Override
        return execute(new InputStreamParser());
    }
    @Override
    public <T> ResponseFuture<T> as(AsyncParser<T> parser) {
        return execute(parser);
    }
    @Override
    public <F extends OutputStreamResponseFuture<F> write(F outputStreamboolean close) {
        return execute(new OutputStreamDataSink(.getServer(), outputStream), closeoutputStream);
    }
    @Override
    public <F extends OutputStreamResponseFuture<F> write(F outputStream) {
        return execute(new OutputStreamDataSink(.getServer(), outputStream), trueoutputStream);
    }
    @Override
    public EmitterTransform<Filewrite(final File file) {
        return execute(new FileDataSink(.getServer(), file), truefilenew Runnable() {
            @Override
            public void run() {
                file.delete();
            }
        });
    }
    @Override
    public IonRequestBuilder setBodyParameter(String nameString value) {
        if ( == null) {
             = new Multimap();
            setBody(new UrlEncodedFormBody());
        }
        if (value != null)
            .add(namevalue);
        return this;
    }
    public IonRequestBuilder setBodyParameters(Map<StringList<String>> params) {
       if ( == null) {
            = new Multimap();
           setBody(new UrlEncodedFormBody());
       }
       .putAll(params);
       return this;
    }
    @Override
    public IonRequestBuilder setMultipartFile(String nameFile file) {
        return setMultipartFile(namenullfile);
    }
    @Override
    public IonRequestBuilder setMultipartFile(String nameString contentTypeFile file) {
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        FilePart part = new FilePart(namefile);
        if (contentType == null)
            contentType = AsyncHttpServer.tryGetContentType(file.getAbsolutePath());
        if (contentType != null)
            part.setContentType(contentType);
        .addPart(part);
        return this;
    }
    @Override
    public IonRequestBuilder setMultipartParameter(String nameString value) {
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        if (value != null)
            .addStringPart(namevalue);
        return this;
    }
    @Override
        for (String keyparams.keySet()) {
            for (String valueparams.get(key)) {
                if (value != null)
                    setMultipartParameter(keyvalue);
            }
        }
        return this;
    }
    @Override
    public IonRequestBuilder addMultipartParts(Iterable<Partparameters) {
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        for (Part partparameters) {
            .addPart(part);
        }
        return this;
    }
    @Override
    public Builders.Any.M addMultipartParts(Part... parameters) {
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        for (Part partparameters) {
            .addPart(part);
        }
        return this;
    }
    @Override
    public IonRequestBuilder setMultipartContentType(String contentType) {
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        .setContentType(contentType);
        return this;
    }
    @Override
        return new IonImageViewRequestBuilder(this);
    }
    @Override
    public ImageViewFuture intoImageView(ImageView imageView) {
        return new IonImageViewRequestBuilder(this).withImageView(imageView).intoImageView(imageView);
    }
    @Override
    public IonRequestBuilder load(File file) {
        loadInternal(nullfile.toURI().toString());
        return this;
    }
    @Override
    public BitmapInfo asCachedBitmap() {
        return new IonImageViewRequestBuilder(this).asCachedBitmap();
    }
    @Override
        return new IonImageViewRequestBuilder(this).isLocallyCached();
    }
    @Override
    public Future<Bitmap> asBitmap() {
        return new IonImageViewRequestBuilder(this).asBitmap();
    }
    String logTag;
    int logLevel;
    @Override
    public IonRequestBuilder setLogging(String tagint level) {
         = tag;
         = level;
        return this;
    }
    @Override
    public <T> ResponseFuture<T> as(Class<T> clazz) {
        return execute(new GsonSerializer<T>(.configure().getGson(), clazz));
    }
    @Override
    public <T> ResponseFuture<T> as(TypeToken<T> token) {
        return execute(new GsonSerializer<T>(.configure().getGson(), token));
    }
    @Override
    public FutureBuilder group(Object groupKey) {
        if ( == null)
             = new ArrayList<WeakReference<Object>>();
        .add(new WeakReference<Object>(groupKey));
        return this;
    }
    int proxyPort;
    @Override
    public IonRequestBuilder proxy(String hostint port) {
         = host;
         = port;
        return this;
    }
    @Override
    public IonRequestBuilder setJsonPojoBody(Object objectTypeToken token) {
        setBody(new PojoBody(.configure().getGson(), objecttoken));
        return this;
    }
    @Override
    public IonRequestBuilder setJsonPojoBody(Object object) {
        setBody(new PojoBody(.configure().getGson(), objectnull));
        return this;
    }
    @Override
    public IonRequestBuilder basicAuthentication(String usernameString password) {
        return setHeader("Authorization""Basic " + Base64.encodeToString(String.format("%s:%s"usernamepassword).getBytes(), Base64.NO_WRAP));
    }
    @Override
    public Builders.Any.B uploadProgress(ProgressCallback callback) {
         = callback;
        return this;
    }
    ProgressBar uploadProgressBar;
    @Override
    public Builders.Any.B uploadProgressBar(ProgressBar progressBar) {
         = progressBar;
        return this;
    }
    ProgressDialog uploadProgressDialog;
    @Override
    public Builders.Any.B uploadProgressDialog(ProgressDialog progressDialog) {
         = progressDialog;
        return this;
    }
    @Override
    public Builders.Any.B uploadProgressHandler(ProgressCallback callback) {
         = callback;
        return this;
    }
    @Override
    public Builders.Any.B onHeaders(HeadersCallback callback) {
         = callback;
        return this;
    }
    @Override
    public Builders.Any.F setDocumentBody(Document document) {
        setBody(new DocumentBody(document));
        return this;
    }
    @Override
    public ResponseFuture<DocumentasDocument() {
        return execute(new DocumentParser());
    }
    @Override
    public Builders.Any.F setFileBody(File file) {
        setBody(new FileBody(file));
        return this;
    }
    @Override
    public Builders.Any.F setByteArrayBody(byte[] bytes) {
        if (bytes != null)
            setBody(new StreamBody(new ByteArrayInputStream(bytes), bytes.length));
        return this;
    }
    @Override
    public Builders.Any.F setStreamBody(InputStream inputStream) {
        setBody(new StreamBody(inputStream, -1));
        return this;
    }
    @Override
    public Builders.Any.F setStreamBody(InputStream inputStreamint length) {
        setBody(new StreamBody(inputStreamlength));
        return this;
    }