Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade Mapzen Android SDK #822

Merged
merged 4 commits into from
Jun 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
buildscript {
ext.kotlin_version = '1.0.4'
ext.kotlin_version = '1.1.2'
ext.dagger_version = '2.0'
repositories {
mavenCentral()
Expand Down Expand Up @@ -125,7 +125,7 @@ dependencies {
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:support-v4:25.1.0'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.mapzen:mapzen-android-sdk:1.3.0-SNAPSHOT'
compile 'com.mapzen:mapzen-android-sdk:1.4.0'
compile "com.google.dagger:dagger:$dagger_version"
compile 'com.squareup:otto:1.3.7'
compile 'com.splunk.mint:mint:4.2.1'
Expand Down
18 changes: 14 additions & 4 deletions app/src/main/java/com/mapzen/erasermap/AndroidModule.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.mapzen.erasermap;

import com.mapzen.android.core.ApiKeyConstants;
import com.mapzen.android.search.MapzenSearch;
import com.mapzen.erasermap.model.AndroidAppSettings;
import com.mapzen.erasermap.model.ApiKeys;
Expand Down Expand Up @@ -33,7 +32,9 @@
import com.squareup.otto.Bus;

import android.content.Context;
import android.os.Build;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -44,6 +45,8 @@

@Module
public class AndroidModule {
private static final int KITKAT = 19;

private final EraserMapApplication application;

public AndroidModule(EraserMapApplication application) {
Expand Down Expand Up @@ -91,8 +94,15 @@ public AndroidModule(EraserMapApplication application) {
}

@Provides @Singleton TileHttpHandler provideTileHttpHandler(ApiKeys apiKeys) {
final TileHttpHandler handler = new TileHttpHandler(application);
handler.setApiKey(apiKeys.getApiKey());
final TileHttpHandler handler;
if (Build.VERSION.SDK_INT >= KITKAT) {
File httpCache = new File(application.getExternalCacheDir().getAbsolutePath() +
"/tile_cache");
int size = 30 * 1024 * 1024;
handler = new TileHttpHandler(httpCache, size);
} else {
handler = new TileHttpHandler();
}
return handler;
}

Expand All @@ -116,7 +126,7 @@ public AndroidModule(EraserMapApplication application) {

@Override public Map<String, String> queryParamsForRequest() {
Map<String, String> params = new HashMap<>();
params.put(ApiKeyConstants.API_KEY, apiKeys.getApiKey());
params.put(Http.PARAM_API_KEY, apiKeys.getApiKey());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe requires more changes (than we want with EM), but probably we should use sceneUpdate with sceneLoad for consistency with SDK usage.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for interaction with Pelias so we need to append the api key. When mapzen/android#412 merges, we can use the new MapzenSearchHttpRequestHandler to append only the DNT header (the api key will be handled by the SDK)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh, yes make sense. 👍

return params;
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ class MainActivity : AppCompatActivity(), MainViewController,
}

private fun initMapzenMap() {
mapView.getMapAsync(apiKeys.apiKey, {
mapView.getMapAsync({
this.mapzenMap = it
configureMapzenMap()
presenter.onRestoreMapState()
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/kotlin/com/mapzen/erasermap/model/ApiKeys.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mapzen.erasermap.model

import com.mapzen.android.core.MapzenManager
import com.mapzen.erasermap.BuildConfig
import com.mapzen.erasermap.EraserMapApplication

Expand All @@ -24,6 +25,7 @@ class ApiKeys private constructor(val application: EraserMapApplication) {
init {
configureKeys()
if (apiKey.isEmpty()) throw IllegalArgumentException("Api key cannot be empty.")
MapzenManager.instance(application).apiKey = apiKey
}

private fun configureKeys() {
Expand Down
1 change: 1 addition & 0 deletions app/src/main/kotlin/com/mapzen/erasermap/model/Http.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
public interface Http {
String HEADER_DNT = "DNT";
String VALUE_HEADER_DNT = "1";
String PARAM_API_KEY = "api_key";
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,6 @@ public class MapzenLocationImpl(val locationClientManager: LocationClientManager
override fun onLocationChanged(location: Location) {
onLocationUpdate(location)
}

override fun onProviderDisabled(provider: String) {

}

override fun onProviderEnabled(provider: String) {

}
}

private val request = LocationRequest.create()
Expand All @@ -60,7 +52,8 @@ public class MapzenLocationImpl(val locationClientManager: LocationClientManager
LocationServices.FusedLocationApi?.setMockLocation(locationClient, settings.mockLocation)
}
if (settings.isMockRouteEnabled) {
LocationServices.FusedLocationApi?.setMockTrace(locationClient, settings.mockRoute)
LocationServices.FusedLocationApi?.setMockTrace(locationClient, settings.mockRoute?.path,
settings.mockRoute?.name)
}
}

Expand Down
33 changes: 8 additions & 25 deletions app/src/main/kotlin/com/mapzen/erasermap/model/TileHttpHandler.kt
Original file line number Diff line number Diff line change
@@ -1,33 +1,16 @@
package com.mapzen.erasermap.model

import android.app.Application
import android.os.Build
import com.mapzen.tangram.HttpHandler
import com.squareup.okhttp.Callback
import okhttp3.Callback
import java.io.File

public class TileHttpHandler(application: Application) : HttpHandler() {
companion object {
@JvmStatic val KITKAT = 19
}

init {
if (Build.VERSION.SDK_INT >= KITKAT) {
val httpCache = File(application.externalCacheDir.absolutePath + "/tile_cache")
setCache(httpCache, 30 * 1024 * 1024)
}
okRequestBuilder.addHeader(Http.HEADER_DNT, Http.VALUE_HEADER_DNT)
}
class TileHttpHandler : TmpHttpHandler {
constructor() : super() {}

var apiKey: String? = null

override fun onRequest(url: String, callback: Callback): Boolean {
val urlWithApiKey = url + "?api_key=" + apiKey
return super.onRequest(urlWithApiKey, callback)
}
constructor(cacheDir: File, cacheSize: Long) : super(cacheDir, cacheSize) {}

override fun onCancel(url: String) {
val urlWithApiKey = url + "?api_key=" + apiKey
super.onCancel(urlWithApiKey)
override fun onRequest(url: String, headers: Map<String, String>, callback: Callback): Boolean {
val emHeaders = mutableMapOf(Http.HEADER_DNT to Http.VALUE_HEADER_DNT)
emHeaders.putAll(headers)
return super.onRequest(url, emHeaders, callback)
}
}
182 changes: 182 additions & 0 deletions app/src/main/kotlin/com/mapzen/erasermap/model/TmpHttpHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package com.mapzen.erasermap.model;

import com.mapzen.tangram.HttpHandler;

import android.os.Build;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionSpec;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.TlsVersion;

/**
* Temporary TileHttpHandler super class until Tangram allows customizing headers.
*/
public class TmpHttpHandler extends HttpHandler {

private OkHttpClient okClient;

/**
* Enables TLS v1.2 when creating SSLSockets.
* <p/>
* For some reason, android supports TLS v1.2 from API 16, but enables it by
* default only from API 20.
*
* @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html
* @see SSLSocketFactory
*/
private class Tls12SocketFactory extends SSLSocketFactory {
private final String[] TLS_V12_ONLY = {"TLSv1.2"};

final SSLSocketFactory delegate;

public Tls12SocketFactory(SSLSocketFactory base) {
this.delegate = base;
}

@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws
IOException {
return patch(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return patch(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket patch(Socket s) {
if (s instanceof SSLSocket) {
((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
}
return s;
}
}

/**
* Construct an {@code HttpHandler} with default options.
*/
public TmpHttpHandler() {
this(null, 0);
}

/**
* Construct an {@code HttpHandler} with cache.
* Cache map data in a directory with a specified size limit
* @param directory Directory in which map data will be cached
* @param maxSize Maximum size of data to cache, in bytes
*/
public TmpHttpHandler(File directory, long maxSize) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS);

if (directory != null && maxSize > 0) {
builder.cache(new Cache(directory, maxSize));
}

if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
builder.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();

List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);

builder.connectionSpecs(specs);
} catch (Exception exc) {
android.util.Log.e("Tangram", "Error while setting TLS 1.2", exc);
}
}

okClient = builder.build();
}

/**
* Begin an HTTP request
* @param url URL for the requested resource
* @param cb Callback for handling request result
* @return true if request was successfully started
*/
public boolean onRequest(String url, Map<String, String> headers, Callback cb) {
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers))
.build();
okClient.newCall(request).enqueue(cb);
return true;
}

/**
* Cancel an HTTP request
* @param url URL of the request to be cancelled
*/
public void onCancel(String url) {

// check and cancel running call
for (Call runningCall : okClient.dispatcher().runningCalls()) {
if (runningCall.request().url().toString().equals(url)) {
runningCall.cancel();
}
}

// check and cancel queued call
for (Call queuedCall : okClient.dispatcher().queuedCalls()) {
if (queuedCall.request().url().toString().equals(url)) {
queuedCall.cancel();
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class ValhallaHttpHandler extends TurnByTurnHttpHandler {

private String apiKey = "";

public ValhallaHttpHandler(String endpoint, HttpLoggingInterceptor.Level logLevel) {
configure(endpoint, logLevel);
}
Expand All @@ -19,11 +22,21 @@ public ValhallaHttpHandler(HttpLoggingInterceptor.Level logLevel) {
configure(DEFAULT_URL, logLevel);
}

public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}

@Override
protected Response onRequest(Interceptor.Chain chain) throws IOException {
final HttpUrl url = chain.request()
.url()
.newBuilder()
.addQueryParameter(Http.PARAM_API_KEY, apiKey)
.build();
final Request request = chain.request()
.newBuilder()
.addHeader(Http.HEADER_DNT, Http.VALUE_HEADER_DNT)
.url(url)
.build();
return chain.proceed(request);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ValhallaRouteManager(val settings: AppSettings,
val router = getInitializedRouter(type)

if (location.hasBearing()) {
router.setLocation(start, location.bearing)
router.setLocation(start, location.bearing.toInt())
} else {
router.setLocation(start)
}
Expand Down
Loading