summaryrefslogtreecommitdiff
path: root/platform/android/src/http_request_android.cpp
blob: 1e0039cdf86fec0e3887ee2f0322cc885ce7f350 (plain)
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
#include <mbgl/storage/http_context_base.hpp>
#include <mbgl/storage/http_request_base.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/platform/log.hpp>

#include <mbgl/util/async_task.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/string.hpp>

#include <jni/jni.hpp>
#include "attach_env.hpp"

namespace mbgl {
namespace android {

class HTTPContext : public HTTPContextBase {
public:
    HTTPRequestBase* createRequest(const Resource&, HTTPRequestBase::Callback) final;
    UniqueEnv env { android::AttachEnv() };
};

class HTTPRequest : public HTTPRequestBase {
public:
    static constexpr auto Name() { return "com/mapbox/mapboxsdk/http/HTTPRequest"; };

    HTTPRequest(jni::JNIEnv&, const Resource&, Callback);

    void cancel() final;

    void onFailure(jni::JNIEnv&, int type, jni::String message);
    void onResponse(jni::JNIEnv&, int code,
                    jni::String etag, jni::String modified,
                    jni::String cacheControl, jni::String expires,
                    jni::Array<jni::jbyte> body);

    static jni::Class<HTTPRequest> javaClass;
    jni::UniqueObject<HTTPRequest> javaRequest;

private:
    void finish();

    std::unique_ptr<Response> response;
    const std::shared_ptr<const Response> existingResponse;

    util::AsyncTask async;

    static const int connectionError = 0;
    static const int temporaryError = 1;
    static const int permanentError = 2;
};

jni::Class<HTTPRequest> HTTPRequest::javaClass;

void RegisterNativeHTTPRequest(jni::JNIEnv& env) {
    HTTPRequest::javaClass = *jni::Class<HTTPRequest>::Find(env).NewGlobalRef(env).release();

    #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod<decltype(MethodPtr), (MethodPtr)>(name)

    jni::RegisterNativePeer<HTTPRequest>(env, HTTPRequest::javaClass, "mNativePtr",
        METHOD(&HTTPRequest::onFailure, "nativeOnFailure"),
        METHOD(&HTTPRequest::onResponse, "nativeOnResponse"));
}

// -------------------------------------------------------------------------------------------------

HTTPRequestBase* HTTPContext::createRequest(const Resource& resource, HTTPRequestBase::Callback callback) {
    return new HTTPRequest(*env, resource, callback);
}

HTTPRequest::HTTPRequest(jni::JNIEnv& env, const Resource& resource_, Callback callback_)
    : HTTPRequestBase(resource_, callback_),
      async([this] { finish(); }) {
    std::string etagStr;
    std::string modifiedStr;

    if (resource.priorEtag) {
        etagStr = *resource.priorEtag;
    } else if (resource.priorModified) {
        modifiedStr = util::rfc1123(*resource.priorModified);
    }

    jni::UniqueLocalFrame frame = jni::PushLocalFrame(env, 10);

    static auto constructor =
        javaClass.GetConstructor<jni::jlong, jni::String, jni::String, jni::String, jni::String>(env);

    javaRequest = javaClass.New(env, constructor,
        reinterpret_cast<jlong>(this),
        jni::Make<jni::String>(env, resource.url),
        jni::Make<jni::String>(env, "MapboxGL/1.0"),
        jni::Make<jni::String>(env, etagStr),
        jni::Make<jni::String>(env, modifiedStr)).NewGlobalRef(env);
}

void HTTPRequest::cancel() {
    UniqueEnv env = android::AttachEnv();

    static auto cancel = javaClass.GetMethod<void ()>(*env, "cancel");

    javaRequest->Call(*env, cancel);

    delete this;
}

void HTTPRequest::finish() {
    assert(response);
    notify(*response);

    delete this;
}

void HTTPRequest::onResponse(jni::JNIEnv& env, int code,
                             jni::String etag, jni::String modified, jni::String cacheControl,
                             jni::String expires, jni::Array<jni::jbyte> body) {
    response = std::make_unique<Response>();
    using Error = Response::Error;

    if (etag) {
        response->etag = jni::Make<std::string>(env, etag);
    }

    if (modified) {
        response->modified = util::parseTimePoint(jni::Make<std::string>(env, modified).c_str());
    }

    if (cacheControl) {
        response->expires = parseCacheControl(jni::Make<std::string>(env, cacheControl).c_str());
    }

    if (expires) {
        response->expires = util::parseTimePoint(jni::Make<std::string>(env, expires).c_str());
    }

    if (code == 200) {
        if (body) {
            auto data = std::make_shared<std::string>(body.Length(env), char());
            jni::GetArrayRegion(env, *body, 0, data->size(), reinterpret_cast<jbyte*>(&(*data)[0]));
            response->data = data;
        } else {
            response->data = std::make_shared<std::string>();
        }
    } else if (code == 204 || (code == 404 && resource.kind == Resource::Kind::Tile)) {
        response->noContent = true;
    } else if (code == 304) {
        response->notModified = true;
    } else if (code == 404) {
        response->error = std::make_unique<Error>(Error::Reason::NotFound, "HTTP status code 404");
    } else if (code >= 500 && code < 600) {
        response->error = std::make_unique<Error>(Error::Reason::Server, std::string{ "HTTP status code " } + std::to_string(code));
    } else {
        response->error = std::make_unique<Error>(Error::Reason::Other, std::string{ "HTTP status code " } + std::to_string(code));
    }

    async.send();
}

void HTTPRequest::onFailure(jni::JNIEnv& env, int type, jni::String message) {
    std::string messageStr = jni::Make<std::string>(env, message);

    response = std::make_unique<Response>();
    using Error = Response::Error;

    switch (type) {
        case connectionError:
            response->error = std::make_unique<Error>(Error::Reason::Connection, messageStr);
            break;
        case temporaryError:
            response->error = std::make_unique<Error>(Error::Reason::Server, messageStr);
            break;
        default:
            response->error = std::make_unique<Error>(Error::Reason::Other, messageStr);
    }

    async.send();
}

} // namespace android

std::unique_ptr<HTTPContextBase> HTTPContextBase::createContext() {
    return std::make_unique<android::HTTPContext>();
}

uint32_t HTTPContextBase::maximumConcurrentRequests() {
    return 20;
}

} // namespace mbgl