GithubHelp home page GithubHelp logo

wasp's Introduction

Android Arsenal API Join the chat at https://gitter.im/orhanobut/wasp

Deprecated

Unfortunately due to many reasons including maintenance cost, this library is deprecated. I recommend to use Retrofit/OkHttp instead. Currently this project only aims to provide some experimental functionalities.

Wasp

A compact and easy to use, 'all-in-one' network solution.

The problem

When it comes to daily development, you need more than just a library to handle networking, you need to handle mocking calls, using multiple end points, handling certificates and cookies and many other boiler plate code. With wasp, you can easily handle everything.

Wasp internally uses:

  • Volley for the network stack
  • Gson for parsing
  • OkHttp for the http stack

Wasp provides:

  • Easy implementation
  • MOCK response via text file or auto generated from model class!
  • Request Interceptors to add attributes (query params, headers, retry policy) to each call
  • Api call based headers
  • Api call based end point
  • Api call based retry policy
  • Cookie management
  • Certificate management
  • Painless Image loading
  • RxJava support
  • Request cancelation
  • Sync request call
  • Async request call

Wasp aims :

  • There are many open issues to contribute. Get this chance to contribute and improve your knowledge!
  • We want to make something that is useful and also motivates people to contribute

Add dependency

More info https://jitpack.io/#orhanobut/wasp/1.15

repositories {
  // ...
  maven { url "https://jitpack.io" }
}

dependencies {
  compile 'com.github.orhanobut:wasp:1.15'
}

Create a service interface

public interface GitHubService {

  // Async call
  @GET("/repos/{id}")
  void getRepo(@Path("id") String id, Callback<Repo> callback);
  
  // Async call with WaspRequest (cancelable)
  @GET("/repos/{id}")
  WaspRequest getRepo(@Path("id") String id, Callback<Repo> callback);
    
  // Rx
  @Mock
  @POST("/repos")
  Observable<Repo> createRepo(@Body Repo repo);
  
  // sync call
  @GET("/users/{id}")
  User getUser(@Path("id") String id);
}

Initialize the wasp

GitHubService service = new Wasp.Builder(this)
  .setEndpoint("https://api.github.com")
  .setRequestInterceptor                     // Optional
  .trustCertificates                         // Optional
  .setHttpStack                              // Optional
  .enableCookies                             // Optional
  .setNetworkMode(NetworkMode.MOCK)          // Optional(Used for Mock)
  .build()
  .create(GitHubService.class);

And use it everywhere!

Async

service.getRepo(id, new Callback<Repo>{

  @Override
  public void onSuccess(Response response, Repo repo) {
    // do something
  }
  
  @Override
  public void onError(WaspError error) {
    // handle error
  }
});

Async with WaspRequest (cancelable)

WaspRequest request = service.getRepo(id, new Callback<Repo>{

  @Override
  public void onSuccess(Response response, Repo repo) {
    // do something
  }
  
  @Override
  public void onError(WaspError error) {
    // handle error
  }
});
request.cancel();  //cancels the request

Rx

Observable<Repo> observable = service.createRepo(repo);

Sync

User user = service.getUser(id);

Check wiki for more details

License

Copyright 2014 Orhan Obut

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

wasp's People

Contributors

alexbalo avatar gitter-badger avatar iraycd avatar kardeslik avatar oguzbabaoglu avatar orhanobut avatar tasomaniac avatar y-yagi avatar yekmer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wasp's Issues

shows wrong image while actual image is loading

I have many images in recyclerview. If scrolls to bottom fastly when the application is opened, imageview shows wrong image while actual image is loading. Generally it shows image loaded in previous imageview. When the actual image is loaded, it shows correct image. But it's bad.

A loading spinner should be shown while image is loading.

Mock json error must be catched

When mock json is incorrect or has error library dont catch gson exception so dont call Callback onError method. We can see excepiton from logcat but it must call also onError

at com.google.gson.Gson.fromJson(Gson.java:815)
at com.google.gson.Gson.fromJson(Gson.java:770)
at com.google.gson.Gson.fromJson(Gson.java:719)
at com.orhanobut.wasp.parsers.GsonParser.fromBody(GsonParser.java:32)
at com.orhanobut.wasp.MockNetworkStack.invokeRequest(MockNetworkStack.java:53)
at com.orhanobut.wasp.NetworkHandler.invoke(NetworkHandler.java:116)

Uploading big files

We should introduce File class in order to upload/download big files. This can stay for now but in the future we should think and discuss about it.

Wasp.File

How to use with eclipse

Excuse me,I'm from China,I have never before use Gradle and I have been using Eclipse develop Android applications,so I always import the jar file to my application,this wasp I'm download the source code and compile it,but it's very diffcult to me, because I must download and complie with volley,okhttp,okIo and so on,so I want to ask if have any way to use wasp easiler in eclipse or with out Gradle,e.g. is there a comlied jar file to import,Thank you!

VolleyNetworkStack : why RequestQueue requestQueue is static ?

If I have two services when creating the second one it will call again VolleyNetworkStack.newInstance which will call the constructor again and because requestQueue is static it will override the previous one.
So for exemple if in my first service i need to trust a specific certificate, i will not be able to connect to my web service anymore.
I think it should be something like this :

private RequestQueue requestQueue;

private VolleyNetworkStack(Context context, WaspHttpStack stack) {
    requestQueue = Volley.newRequestQueue(context, (HttpStack) stack.getHttpStack());
}

static VolleyNetworkStack newInstance(Context context, WaspHttpStack stack) {
    return new VolleyNetworkStack(context, stack);
}

RequestQueue getRequestQueue() {
    if (requestQueue == null) {
        throw new NullPointerException("Wasp.Builder must be called");
    }
    return requestQueue;
}

OkHttpStack gives NPE

Null check must be added for "body.contentType()" in "OkHttpStack.entityFromOkHttpResponse" method.

Add chunk feature to logging

Android logger's max entry length is limited with ~4076 bytes. So, we should add this feature to be able to see whole request/response when the length is longer than the max limit.

java.io.InterruptedIOException: timeout

Hey all,

I have two activities (activity_main and activity_test) in my Android App (just a test application). Each of them has a button. If this will be clicked a login request will be sent over wasp to my server and then the other activity will be opened. When I start another app and then going back to the test App, I get this exception: java.io.InterruptedIOException: timeout after sending several requests again. If you wait about 10 seconds you can send request without the error (exception).

Here the full log, the first request is successful but the other ones throwing the InterruptedIOException:

07-07 08:14:50.129  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> REQUEST POST https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:50.129  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Content-Type: application/json]
07-07 08:14:50.133  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - {"email":"[email protected]","password":"test12"}
07-07 08:14:50.133  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> END
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- RESPONSE 200 https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Access-Control-Allow-Credentials: true]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Access-Control-Allow-Headers: auth_token, main_category_id, Content-Type]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Access-Control-Allow-Methods: GET, POST, DELETE, PUT]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Access-Control-Allow-Origin: *]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Cache-Control: no-cache, no-transform, must-revalidate]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Connection: keep-alive]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Content-Length: 53]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Content-Type: application/json]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Date: Tue, 07 Jul 2015 08:14:50 GMT]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [OkHttp-Received-Millis: 1436256890275]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [OkHttp-Selected-Protocol: http/1.1]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [OkHttp-Sent-Millis: 1436256890141]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Server: nginx/1.4.6 (Ubuntu)]
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - {"auth_token":"e245bd5c-f102-4f91-8cd0-97c96c8581b7"}
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- END (Size: 53 bytes - Network time: 139 ms)
07-07 08:14:50.273  25489-25489/com.example.root.wasptest D/Login﹕ e245bd5c-f102-4f91-8cd0-97c96c8581b7
07-07 08:14:50.345  25489-25489/com.example.root.wasptest W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-07 08:14:50.913  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> REQUEST POST https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:50.913  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Content-Type: application/json]
07-07 08:14:50.913  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - {"email":"[email protected]","password":"test12"}
07-07 08:14:50.913  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> END
07-07 08:14:52.493  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> REQUEST POST https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:52.493  25489-25489/com.example.root.wasptest D/Wasp﹕ Header - [Content-Type: application/json]
07-07 08:14:52.493  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - {"email":"[email protected]","password":"test12"}
07-07 08:14:52.493  25489-25489/com.example.root.wasptest D/Wasp﹕ ---> END
07-07 08:14:53.421  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- ERROR
07-07 08:14:53.421  25489-25489/com.example.root.wasptest D/Wasp﹕ Message - [java.io.InterruptedIOException: timeout]
07-07 08:14:53.421  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- RESPONSE 0 https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:53.421  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - no body
07-07 08:14:53.421  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- END (Size: 0 bytes - Network time: 5778 ms)
07-07 08:14:53.421  25489-25489/com.example.root.wasptest E/Login﹕ java.io.InterruptedIOException: timeout
07-07 08:14:55.993  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- ERROR
07-07 08:14:55.993  25489-25489/com.example.root.wasptest D/Wasp﹕ Message - [java.io.InterruptedIOException: timeout]
07-07 08:14:55.993  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- RESPONSE 0 https://h2211501.stratoserver.net/bachelor_webservice/resources/session/login
07-07 08:14:55.993  25489-25489/com.example.root.wasptest D/Wasp﹕ Body - no body
07-07 08:14:55.993  25489-25489/com.example.root.wasptest D/Wasp﹕ <--- END (Size: 0 bytes - Network time: 7382 ms)

Here is my source code. Did I do something wrong or is it a bug?
In the following I show just the MainActivity because the other one (TestActitvity) is exactly the same except that the MainActivity will be started.

WaspApplication.java

public class WaspApplication extends Application {
    private static WaspService service;

    public static WaspService getService(){
        return service;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        service = new Wasp.Builder(this)
                .setEndpoint("https://h2211501.stratoserver.net/bachelor_webservice/resources")
                .setLogLevel(LogLevel.FULL)
                .trustCertificates()
                .build()
                .create(WaspService.class);
    }
}

WaspService.java

public interface WaspService {

    //---Static header
    @Headers("Content-Type:application/json")

    @POST("/session/login")
    WaspRequest login(
            @Body LoginData loginData,
            Callback<LoginResponse> callBack
    );
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private final RequestManager requestManager = new SimpleRequestManager();

    private final WaspService service = WaspApplication.getService();
    private LoginData loginData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loginData = new LoginData();
        loginData.setEmail("[email protected]");
        loginData.setPassword("test12");

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WaspRequest request = service.login(loginData, callbackLogin);
                requestManager.addRequest(request);
            }
        });


    }

    ...
    ...

    private final Callback<LoginResponse> callbackLogin = new Callback<LoginResponse>() {
        @Override
        public void onSuccess(Response response, LoginResponse loginResponse) {
            Log.d("Login", loginResponse.getToken());
            startTestActivity();
        }

        @Override
        public void onError(WaspError waspError) {
            Log.e("Login", waspError.getErrorMessage());
        }
    };

    private void startTestActivity(){
        startActivity(new Intent(this, TestActivity.class));
        finish();
    }
}

MockFactory does not set Response Object

The response object created by MockFactory should have a response object set.

WaspResponse waspResponse = new WaspResponse.Builder()
                .setUrl(waspRequest.getUrl())
                .setStatusCode(statusCode)
                .setHeaders(Collections.<String, String>emptyMap())
                .setBody(responseString)
                .setLength(responseString.length())
                .setNetworkTime(0)
                .setResponseObject(object) // <-- This is missing.
                .build();

WaspCache improvement

Currently we use our implementation for cache in order to learn better. We should improve this class as much as possible with the new ideas. Please put your idea here and let's discuss before implementing.

POST Field annotation

There is currently no way to do a normal form POST. The @field annotation from retrofit is missing in this library

Cancel Request

Client should be able to cancel the specific request or requests in a very easy way. We should really discuss about this carefully.

Please consider following items for the suggestions:

  • We don't want to make the logic complex, the steps should be really easy for the client.
  • The solution should follow the design principles. Decoupling is really important for us, we don't want to rely only volley since it's just a network stack that we use for now.

Disk cache

We need to add disk cache for the image caching

The sample stopped when LISTVIEW&RECYCLERVIEW clicked

java.lang.ClassCastException: com.orhanobut.wasp.WaspOkHttpStack cannot be cast to com.android.volley.toolbox.HttpStack
at com.orhanobut.wasp.VolleyImageNetworkHandler.(VolleyImageNetworkHandler.java:28)

this.requestQueue = Volley.newRequestQueue(context, (HttpStack) httpStack);

should become

this.requestQueue = Volley.newRequestQueue(context, httpStack.getHttpStack());

?

Wasp.Image load to target

We need a solution to load images into target, which may be used for textview compounds instead of imageview.

RequestInterceptor simplify

I think we should simplify requestInterceptor. Currently methods must be overriden but we can do that with only one method overriding which contains the requestinterceptor and interceptor can add headers/auth/queryparams

WaspError should expose response body

There should be a method for getting response body. Moreover, it would be good if WaspError could provide a method which will get a type and return an instance of that type created from response body.

BitmapWaspCache should be a single instance.

I add some logs in WaspImageHandler.java like,
final String cacheKey = StringUtils.getCacheKey(url, maxWidth, maxHeight);
final Bitmap bitmap = imageCache.getBitmap(cacheKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
Log.d("wasp","cache image : " + url);
return;
} else {
Log.d("wasp","no use cache image : " + url);
}

the print log is,
03-20 23:12:28.068 22170-22170/com.orhanobut.waspsample D/wasp﹕ no use cache image : http://static.cnbetacdn.com/article/2015/0320/3e5026c844185c5.jpg
03-20 23:12:28.068 22170-22170/com.orhanobut.waspsample D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:com.orhanobut.waspsample asetfile:null
03-20 23:12:28.068 22170-22170/com.orhanobut.waspsample D/wasp﹕ no use cache image : http://static.cnbetacdn.com/article/2015/0320/3e5026c844185c5.jpg

onError callback response body null

Hi,
this is my request log :

Wasp﹕ ---> REQUEST GET http://myserver.com/api/Get
Wasp﹕ Header - [basic: test]
Wasp﹕ Body - no body
Wasp﹕ ---> END
Wasp﹕ ---> REQUEST GET http://myserver.com/api/Get
Wasp﹕ Header - [Accept-Encoding: gzip]
Wasp﹕ Header - [basic: test]
Wasp﹕ Header - [Connection: Keep-Alive]
Wasp﹕ Header - [Host: myserver.com]
Wasp﹕ Header - [User-Agent: okhttp/2.2.0]
Wasp﹕ Body - no body
Wasp﹕ ---> END
Wasp﹕ <--- RESPONSE 401 http://myserver.com/api/Get
Wasp﹕ Header - [Cache-Control: no-cache]
Wasp﹕ Header - [Content-Length: 85]
Wasp﹕ Header - [Content-Type: text/plain; charset=utf-8]
Wasp﹕ Header - [Date: Mon, 18 May 2015 09:50:38 GMT]
Wasp﹕ Header - [Expires: -1]
Wasp﹕ Header - [OkHttp-Received-Millis: 1431942628563]
Wasp﹕ Header - [OkHttp-Selected-Protocol: http/1.1]
Wasp﹕ Header - [OkHttp-Sent-Millis: 1431942628400]
Wasp﹕ Header - [Pragma: no-cache]
Wasp﹕ Header - [Server: Microsoft-IIS/7.5]
Wasp﹕ Header - [WWW-Authenticate: Negotiate]
Wasp﹕ Body - There has been an error. try again BODY !!!
Wasp﹕ <--- END (Size: 85 bytes - Network time: 164.154053 ms)
Volley﹕ [2241] BasicNetwork.performRequest: Unexpected response code 401 for http://myserver.com/api/Get
Wasp﹕ <--- ERROR
Wasp﹕ Message - [null]
Wasp﹕ <--- RESPONSE 0 http://myserver.com/api/Get
Wasp﹕ Body - no body
Wasp﹕ <--- END (Size: 0 bytes - Network time: 9386 ms)

Why in callback body is null but it should be : There has been an error. try again BODY !!!

 @Override
                                public void onError(WaspError waspError) {
                                    Log.e("TAG", "test: "+ waspError.getErrorMessage());
                                    Log.e("TAG", "test: "+ waspError.getRespone().getBody());
                                    Log.e("TAG", "test: "+ waspError.getRespone().getStatusCode());
                                }

Multiple image url for the same view

Wasp.Image.from should accept multiple urls and they all should load with the given order. This feature would allow to load the first very low resolution then the next high resolution.

mode selection via builder

Client should be able to select the mode such as Mode.MOCK etc. We need this feature in order to select the mocking or the real implementation. Deleting each mock annotation would take time and add them back will be frustrating.

I suggest the following implementation:

  • In the builder we can introduce a new method which setMode()
  • setMode method should accept Mode.MOCK, Mode.LIVE.
  • default mode should be LIVE.

Convert to Java Lbrary

Should convert to pure Java instead of com.android.library

Java library advantages:

  • Better support for unit testing. (No need for Roboelectric etc.)
  • Faster compile (no dex / resource management)

gradle setup

is this possible to have a gradle setup for us?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.