Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.koushikdutta.ion;
  
  import  android.app.Activity;
  import  android.app.ActivityManager;
  import  android.app.ProgressDialog;
  import  android.app.Service;
  import  android.content.Context;
  import  android.graphics.Bitmap;
  import  android.os.Handler;
 import  android.widget.ImageView;
 import  android.widget.ProgressBar;
 
 import  com.koushikdutta.async.AsyncServer;
 import  com.koushikdutta.async.DataEmitter;
 import  com.koushikdutta.async.DataSink;
 import  com.koushikdutta.async.DataTrackingEmitter;
 import  com.koushikdutta.async.DataTrackingEmitter.DataTracker;
 import  com.koushikdutta.async.FilteredDataEmitter;
 import  com.koushikdutta.async.Util;
 import  com.koushikdutta.async.callback.CompletedCallback;
 import  com.koushikdutta.async.future.Future;
 import  com.koushikdutta.async.future.FutureCallback;
 import  com.koushikdutta.async.future.SimpleFuture;
 import  com.koushikdutta.async.future.TransformFuture;
 import  com.koushikdutta.async.http.AsyncHttpGet;
 import  com.koushikdutta.async.http.AsyncHttpPost;
 import  com.koushikdutta.async.http.AsyncHttpRequest;
 import  com.koushikdutta.async.http.AsyncHttpRequestBody;
 import  com.koushikdutta.async.http.JSONObjectBody;
 import  com.koushikdutta.async.http.Multimap;
 import  com.koushikdutta.async.http.MultipartFormDataBody;
 import  com.koushikdutta.async.http.StringBody;
 import  com.koushikdutta.async.http.UrlEncodedFormBody;
 import  com.koushikdutta.async.parser.AsyncParser;
 import  com.koushikdutta.async.parser.JSONArrayParser;
 import  com.koushikdutta.async.parser.JSONObjectParser;
 import  com.koushikdutta.async.parser.StringParser;
 import  com.koushikdutta.async.stream.OutputStreamDataSink;
 
 import  org.json.JSONArray;
 import  org.json.JSONObject;
 
 import java.io.File;
 import java.net.URI;
 import java.util.List;

Created by koush on 5/21/13.
 
     AsyncHttpRequest request;
     Ion ion;
     WeakReference<Context> context;
 
     public IonRequestBuilder(Context contextIon ion) {
         this. = ion;
         this. = new WeakReference<Context>(context);
     }
 
     @Override
     public IonBodyParamsRequestBuilder load(String url) {
         return loadInternal(AsyncHttpGet.METHOD, url);
     }
 
     private IonBodyParamsRequestBuilder loadInternal(String methodString url) {
          = new AsyncHttpRequest(URI.create(url), method);
         setLogging(..);
         return this;
     }
 
     boolean methodWasSet;
     @Override
     public IonBodyParamsRequestBuilder load(String methodString url) {
          = true;
         return loadInternal(methodurl);
     }
 
     @Override
     public IonBodyParamsRequestBuilder setHeader(String nameString value) {
         .setHeader(namevalue);
         return this;
     }
 
     @Override
     public IonBodyParamsRequestBuilder addHeader(String nameString value) {
         .addHeader(namevalue);
         return this;
     }
    @Override
    public IonBodyParamsRequestBuilder setTimeout(int timeoutMilliseconds) {
        .setTimeout(timeoutMilliseconds);
        return this;
    }
    @Override
    public IonBodyParamsRequestBuilder setHandler(Handler handler) {
        .setHandler(handler);
        return this;
    }
    private <T> IonFutureRequestBuilder setBody(AsyncHttpRequestBody<T> body) {
        .setBody(body);
        if (!)
            .setMethod(AsyncHttpPost.METHOD);
        return this;
    }
    @Override
    public IonFutureRequestBuilder setJSONObjectBody(JSONObject jsonObject) {
        setHeader("Content-Type""application/json");
        return setBody(new JSONObjectBody(jsonObject));
    }
    @Override
    public IonFutureRequestBuilder setStringBody(String string) {
        setHeader("Content-Type""text/plain");
        return setBody(new StringBody(string));
    }
    private static boolean isServiceRunning(Service candidate) {
        ActivityManager manager = (ActivityManager)candidate.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> services = manager.getRunningServices(.);
        if (services == null)
            return false;
        for (ActivityManager.RunningServiceInfo serviceservices) {
            if (candidate.getClass().getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    private boolean checkContext() {
        Context context = IonRequestBuilder.this..get();
        if (context == null)
            return false;
        if (context instanceof Activity) {
            Activity activity = (Activity)context;
            if (activity.isFinishing())
                return false;
        }
        else if (context instanceof Service) {
            Service service = (Service)context;
            if (!isServiceRunning(service))
                return false;
        }
        return true;
    }
    private <T> void postExecute(final SimpleFuture<T> futurefinal Exception exfinal T value) {
        final Runnable runner = new Runnable() {
            @Override
            public void run() {
                // check if the context is still alive...
                if (!checkContext())
                    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 (.getHandler() == null)
            ..getServer().post(runner);
        else
            AsyncServer.post(.getHandler(), runner);
    }
    private <T> void getLoaderEmitter(TransformFuture<T, LoaderEmitterret) {
        if ( == null || .getUri() == null || .getUri().getScheme() == null) {
            ret.setComplete(new Exception("Invalid URI"));
            return;
        }
        for (Loader loader..) {
            Future<DataEmitter> emitter = loader.load(ret);
            if (emitter != null) {
                ret.setParent(emitter);
                return;
            }
        }
        ret.setComplete(new Exception("Unknown uri scheme"));
    }
    private class EmitterTransform<T> extends TransformFuture<T, LoaderEmitter> {
        public EmitterTransform() {
            .addFutureInFlight(this.get());
        }
        DataEmitter emitter;
        @Override
        protected void cancelCleanup() {
            if ( != null)
                .close();
        }
        @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();
            final int total = emitter.length();
            DataTrackingEmitter tracker;
            if (!(emitter instanceof DataTrackingEmitter)) {
                tracker = new FilteredDataEmitter();
                tracker.setDataEmitter(this.);
            }
            else {
                tracker = (DataTrackingEmitter)this.;
            }
            this. = tracker;
            tracker.setDataTracker(new DataTracker() {
                @Override
                public void onData(final int totalBytesRead) {
                    // if the requesting context dies during the transfer... cancel
                    if (!checkContext()) {
                        cancel();
                        return;
                    }
                    int percent = (int)((float)totalBytesRead / total * 100f);
                    if ( != null) {
                        ProgressBar bar = .get();
                        if (bar != null)
                            bar.setProgress(percent);
                    }
                    if ( != null) {
                        ProgressDialog dlg = .get();
                        if (dlg != null)
                            dlg.setProgress(percent);
                    }
                    if ( != null)
                        .onProgress(totalBytesReadtotal);
                    if ( != null) {
                        .getHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                .onProgress(totalBytesReadtotal);
                            }
                        });
                    }
                }
            });
        }
    }
    @Override
    public IonBodyParamsRequestBuilder progressBar(ProgressBar progressBar) {
        this. = new WeakReference<ProgressBar>(progressBar);
        return this;
    }
    @Override
    public IonBodyParamsRequestBuilder progressDialog(ProgressDialog progressDialog) {
        this. = new WeakReference<ProgressDialog>(progressDialog);
        return this;
    }
    WeakReference<ProgressBar> progressBar;
    WeakReference<ProgressDialog> progressDialog;
    @Override
         = callback;
        return this;
    }
    @Override
         = callback;
        return this;
    }
    <T> Future<T> execute(final DataSink sinkfinal boolean closefinal T result) {
        return execute(sinkcloseresultnull);
    }
    <T> Future<T> execute(final DataSink sinkfinal boolean closefinal T resultfinal Runnable cancel) {
        EmitterTransform<T> ret = new EmitterTransform<T>() {
            @Override
            protected void cancelCleanup() {
                super.cancelCleanup();
                if (close)
                    sink.close();
                if (cancel != null)
                    cancel.run();
            }
            TransformFuture<T, LoaderEmitterself = this;
            @Override
            protected void transform(LoaderEmitter emitterthrows Exception {
                super.transform(emitter);
                Util.pump(this.sinknew CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        if (close)
                            sink.close();
                        postExecute(exresult);
                    }
                });
            }
        };
        getLoaderEmitter(ret);
        return ret;
    }
    <T> Future<T> execute(final AsyncParser<T> parser) {
        assert parser != null;
        EmitterTransform<T> ret = new EmitterTransform<T>() {
            TransformFuture<T, LoaderEmitterself = 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;
    }
    @Override
    public Future<JSONObject> asJSONObject() {
        return execute(new JSONObjectParser());
    }
    @Override
    public Future<JSONArray> asJSONArray() {
        return execute(new JSONArrayParser());
    }
    @Override
    public Future<StringasString() {
        return execute(new StringParser());
    }
    @Override
    public <F extends OutputStream> Future<F> write(F outputStreamboolean close) {
        return execute(new OutputStreamDataSink(outputStream), closeoutputStream);
    }
    @Override
    public <F extends OutputStream> Future<F> write(F outputStream) {
        return execute(new OutputStreamDataSink(outputStream), trueoutputStream);
    }
    @Override
    public Future<Filewrite(final File file) {
        try {
            return execute(new OutputStreamDataSink(new FileOutputStream(file)), truefilenew Runnable() {
                @Override
                public void run() {
                    file.delete();
                }
            });
        }
        catch (Exception e) {
            SimpleFuture<Fileret = new SimpleFuture<File>();
            ret.setComplete(e);
            return ret;
        }
    }
    Multimap bodyParameters;
    @Override
        if ( == null) {
             = new Multimap();
            setBody(new UrlEncodedFormBody());
        }
        .add(namevalue);
        return this;
    }
    MultipartFormDataBody multipartBody;
    @Override
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        .addFilePart(namefile);
        return this;
    }
    @Override
        if ( == null) {
             = new MultipartFormDataBody();
            setBody();
        }
        .addStringPart(namevalue);
        return this;
    }
    @Override
        return new IonBitmapRequestBuilder(this);
    }
        return new IonBitmapRequestBuilder(this).withImageView(imageView);
    }
    @Override
    public Future<Bitmap> intoImageView(ImageView imageView) {
        return new IonBitmapRequestBuilder(this).intoImageView(imageView);
    }
    @Override
    public IonFutureRequestBuilder load(File file) {
        loadInternal(nullfile.toURI().toString());
        return this;
    }
    @Override
    public Future<Bitmap> asBitmap() {
        return new IonBitmapRequestBuilder(this).asBitmap();
    }
    @Override
    public IonBodyParamsRequestBuilder setLogging(String tagint level) {
        .setLogging(taglevel);
        return this;
    }
New to GrepCode? Check out our FAQ X