Skip to content
Snippets Groups Projects
Commit 315f78d2 authored by John Carlson's avatar John Carlson
Browse files

API things to Kotlin

parent 9067ed15
No related branches found
No related tags found
No related merge requests found
Showing
with 737 additions and 624 deletions
Loading
Loading
@@ -78,7 +78,7 @@ open class App : Application() {
 
val accounts = Account.getAccounts()
if (!accounts.isEmpty()) {
currentAccount = accounts[0]
setAccount(accounts[0])
}
 
Lift.track(this)
Loading
Loading
Loading
Loading
@@ -164,7 +164,7 @@ class AddUserActivity : MorphActivity() {
teleprinter.hideKeyboard()
swipeRefreshLayout.isRefreshing = true
loading = true
App.get().gitLab.searchUsers(query)
App.get().gitLab.searchUsers(query!!)
.compose(this.bindToLifecycle<Response<List<UserBasic>>>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Loading
Loading
@@ -192,7 +192,7 @@ class AddUserActivity : MorphActivity() {
loading = true
adapter.setLoading(true)
Timber.d("loadMore " + nextPageUrl!!.toString() + " " + query)
App.get().gitLab.searchUsers(nextPageUrl!!.toString(), query)
App.get().gitLab.searchUsers(nextPageUrl!!.toString(), query!!)
.compose(this.bindToLifecycle<Response<List<UserBasic>>>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Loading
Loading
Loading
Loading
@@ -122,7 +122,7 @@ class FileActivity : BaseActivity() {
 
private fun loadData() {
progress.visibility = View.VISIBLE
App.get().gitLab.getFile(projectId, path, ref)
App.get().gitLab.getFile(projectId, path!!, ref!!)
.compose(this.bindToLifecycle<RepositoryFile>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Loading
Loading
Loading
Loading
@@ -110,7 +110,7 @@ class GroupsActivity : BaseActivity() {
nextPageUrl = null
loading = true
 
App.get().gitLab.groups
App.get().gitLab.getGroups()
.compose(this.bindToLifecycle<Response<List<Group>>>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Loading
Loading
Loading
Loading
@@ -198,7 +198,7 @@ class IssueActivity : BaseActivity() {
App.get().gitLab.getProject(projectNamespace, projectName)
.flatMap { project ->
this@IssueActivity.project = project
App.get().gitLab.getIssuesByIid(project.id, issueIid)
App.get().gitLab.getIssuesByIid(project.id, issueIid!!)
}
.compose(this.bindToLifecycle<List<Issue>>())
.subscribeOn(Schedulers.io())
Loading
Loading
Loading
Loading
@@ -341,7 +341,7 @@ class LoginActivity : BaseActivity() {
gitlabClientBuilder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
}
val gitLab = GitLabFactory.create(account, gitlabClientBuilder.build())
gitLab.thisUser
gitLab.getThisUser()
.compose(this.bindToLifecycle<Response<UserFull>>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Loading
Loading
@@ -402,7 +402,7 @@ class LoginActivity : BaseActivity() {
(d.findViewById(android.R.id.message) as TextView).movementMethod = LinkMovementMethod.getInstance()
} else if (t is SSLPeerUnverifiedException && t.message?.toLowerCase()!!.contains("hostname")) {
account.trustedHostname = null
val finalHostname = CustomHostnameVerifier.getLastFailedHostname()
val finalHostname = CustomHostnameVerifier.lastFailedHostname
val d = AlertDialog.Builder(this)
.setTitle(R.string.hostname_title)
.setMessage(R.string.hostname_message)
Loading
Loading
package com.commit451.gitlab.api;
package com.commit451.gitlab.api
 
import com.commit451.gitlab.model.Account;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
import com.commit451.gitlab.model.Account
import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
import java.io.IOException
 
/**
* Adds the private token to all requests
*/
public class AuthenticationRequestInterceptor implements Interceptor {
public static final String AUTHORIZATION_HEADER_FIELD = "Authorization";
public static final String PRIVATE_TOKEN_HEADER_FIELD = "PRIVATE-TOKEN";
private static final String PRIVATE_TOKEN_GET_PARAMETER = "private_token";
private Account account;
class AuthenticationRequestInterceptor(private val account: Account) : Interceptor {
 
public AuthenticationRequestInterceptor(Account account) {
this.account = account;
companion object {
val AUTHORIZATION_HEADER_FIELD = "Authorization"
val PRIVATE_TOKEN_HEADER_FIELD = "PRIVATE-TOKEN"
val PRIVATE_TOKEN_GET_PARAMETER = "private_token"
}
 
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
 
HttpUrl url = request.url();
var url = request.url()
 
String cleanUrl = url.toString();
cleanUrl = cleanUrl.substring(cleanUrl.indexOf(':'));
var cleanUrl = url.toString()
cleanUrl = cleanUrl.substring(cleanUrl.indexOf(':'))
 
String cleanServerUrl = account.getServerUrl().toString();
cleanServerUrl = cleanServerUrl.substring(cleanServerUrl.indexOf(':'));
var cleanServerUrl = account.serverUrl.toString()
cleanServerUrl = cleanServerUrl.substring(cleanServerUrl.indexOf(':'))
 
if (cleanUrl.startsWith(cleanServerUrl)) {
String authorizationHeader = account.getAuthorizationHeader();
val authorizationHeader = account.authorizationHeader
if (authorizationHeader != null) {
request = request.newBuilder()
.header(AUTHORIZATION_HEADER_FIELD, authorizationHeader)
.build();
.build()
}
 
String privateToken = account.getPrivateToken();
val privateToken = account.privateToken
if (privateToken == null) {
Timber.e("The private token was null");
Timber.e("The private token was null")
} else {
url = url.newBuilder()
.addQueryParameter(PRIVATE_TOKEN_GET_PARAMETER, privateToken)
.build();
.build()
 
request = request.newBuilder()
.header(PRIVATE_TOKEN_HEADER_FIELD, privateToken)
.url(url)
.build();
.build()
}
}
 
return chain.proceed(request);
return chain.proceed(request)
}
}
This diff is collapsed.
This diff is collapsed.
package com.commit451.gitlab.api;
package com.commit451.gitlab.api
 
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import com.commit451.gitlab.model.Account;
import com.github.aurae.retrofit2.LoganSquareConverterFactory;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.Executor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import android.support.annotation.VisibleForTesting
import com.commit451.gitlab.model.Account
import com.github.aurae.retrofit2.LoganSquareConverterFactory
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
 
/**
* Pulls all the GitLab stuff from the API
*/
public final class GitLabFactory {
object GitLabFactory {
 
/**
* Create a GitLab get with the current account passed.
* @param account the account to try and log in with
* *
* @return the GitLab get
*/
public static GitLab create(Account account, OkHttpClient client) {
return create(account, client, false);
fun create(account: Account, client: OkHttpClient): GitLab {
return create(account, client, false)
}
 
@VisibleForTesting
public static GitLab create(Account account, OkHttpClient client, boolean dummyExecutor) {
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.baseUrl(account.getServerUrl().toString())
fun create(account: Account, client: OkHttpClient, dummyExecutor: Boolean): GitLab {
val retrofitBuilder = Retrofit.Builder()
.baseUrl(account.serverUrl.toString())
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(LoganSquareConverterFactory.create());
.addConverterFactory(LoganSquareConverterFactory.create())
if (dummyExecutor) {
retrofitBuilder.callbackExecutor(new Executor() {
@Override
public void execute(@NonNull Runnable command) {
//dumb, to prevent tests from failing
}
});
retrofitBuilder.callbackExecutor {
//dumb, to prevent tests from failing }
}
}
return retrofitBuilder.build().create(GitLab.class);
return retrofitBuilder.build().create(GitLab::class.java)
}
}
package com.commit451.gitlab.api;
import com.commit451.gitlab.model.rss.Feed;
import io.reactivex.Single;
import retrofit2.http.GET;
import retrofit2.http.Url;
public interface GitLabRss {
@GET
Single<Feed> getFeed(@Url String url);
}
package com.commit451.gitlab.api
import com.commit451.gitlab.model.rss.Feed
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Url
interface GitLabRss {
@GET
fun getFeed(@Url url: String): Single<Feed>
}
package com.commit451.gitlab.api;
package com.commit451.gitlab.api
 
import com.commit451.gitlab.model.Account;
import com.commit451.gitlab.api.rss.SimpleXmlPersisterFactory;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import org.simpleframework.xml.core.Persister;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import com.commit451.gitlab.api.rss.SimpleXmlPersisterFactory
import com.commit451.gitlab.model.Account
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
 
/**
* Creates RSS get for GitLab
*/
public class GitLabRssFactory {
object GitLabRssFactory {
 
public static GitLabRss create(Account account, OkHttpClient client) {
Persister persister = SimpleXmlPersisterFactory.createPersister(account);
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(account.getServerUrl().toString())
fun create(account: Account, client: OkHttpClient): GitLabRss {
val persister = SimpleXmlPersisterFactory.createPersister(account)
val restAdapter = Retrofit.Builder()
.baseUrl(account.serverUrl.toString())
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(SimpleXmlConverterFactory.create(persister))
.build();
return restAdapter.create(GitLabRss.class);
.build()
return restAdapter.create(GitLabRss::class.java)
}
}
package com.commit451.gitlab.api;
package com.commit451.gitlab.api
 
import com.commit451.gitlab.model.Account;
import com.commit451.gitlab.ssl.CustomTrustManager;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.ssl.CustomTrustManager
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
 
/**
* Creates an OkHttpClient with the needed defaults
*/
public final class OkHttpClientFactory {
public static OkHttpClient.Builder create(Account account) {
return create(account, true);
}
object OkHttpClientFactory {
 
/**
* Creates an {@link OkHttpClient} configured with the account configuration
*
* Creates an [OkHttpClient] configured with the account configuration
* @param account the account
* *
* @param includeSignInAuthenticator include a sign in authenticator that checks signed in status
* @return a configured {@link okhttp3.OkHttpClient.Builder}
* *
* @return a configured [okhttp3.OkHttpClient.Builder]
*/
public static OkHttpClient.Builder create(Account account, boolean includeSignInAuthenticator) {
@JvmOverloads fun create(account: Account, includeSignInAuthenticator: Boolean = true): OkHttpClient.Builder {
// Do we even need a custom trust manager?
// Yep. Otherwise SSL won't work properly with some configurations :) -Michi
CustomTrustManager customTrustManager = new CustomTrustManager();
customTrustManager.setTrustedCertificate(account.getTrustedCertificate());
customTrustManager.setTrustedHostname(account.getTrustedHostname());
customTrustManager.setPrivateKeyAlias(account.getPrivateKeyAlias());
val customTrustManager = CustomTrustManager()
customTrustManager.setTrustedCertificate(account.trustedCertificate)
customTrustManager.setTrustedHostname(account.trustedHostname)
customTrustManager.setPrivateKeyAlias(account.privateKeyAlias)
 
OkHttpClient.Builder builder = new OkHttpClient.Builder()
val builder = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.addInterceptor(new AuthenticationRequestInterceptor(account))
.sslSocketFactory(customTrustManager.getSSLSocketFactory(), X509TrustManagerProvider.INSTANCE.get())
.hostnameVerifier(customTrustManager.getHostnameVerifier());
.addInterceptor(AuthenticationRequestInterceptor(account))
.sslSocketFactory(customTrustManager.getSSLSocketFactory(), X509TrustManagerProvider.get())
.hostnameVerifier(customTrustManager.getHostnameVerifier())
 
if (includeSignInAuthenticator) {
OpenSignInAuthenticator authenticator = new OpenSignInAuthenticator(account);
val authenticator = OpenSignInAuthenticator(account)
builder.authenticator(authenticator)
.proxyAuthenticator(authenticator);
.proxyAuthenticator(authenticator)
}
 
return builder;
return builder
}
}
package com.commit451.gitlab.api;
import android.content.Intent;
import android.widget.Toast;
import com.commit451.gitlab.App;
import com.commit451.gitlab.R;
import com.commit451.gitlab.activity.LoginActivity;
import com.commit451.gitlab.model.Account;
import com.commit451.gitlab.util.ThreadUtil;
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import timber.log.Timber;
/**
* If it detects a 401, redirect the user to the login screen, clearing activity the stack.
* Kinda a weird global way of forcing the user to the login screen if their auth has expired
*/
public class OpenSignInAuthenticator implements Authenticator {
private Account account;
public OpenSignInAuthenticator(Account account) {
this.account = account;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
//Special case for if someone just put in their username or password wrong
if (!"session".equals(response.request().url().pathSegments().get(response.request().url().pathSegments().size()-1))) {
//Off the background thread
Timber.wtf(new RuntimeException("Got a 401 and showing sign in for url: " + response.request().url()));
ThreadUtil.postOnMainThread(new Runnable() {
@Override
public void run() {
//Remove the account, so that the user can sign in again
App.Companion.get().getPrefs().removeAccount(account);
Toast.makeText(App.Companion.get(), R.string.error_401, Toast.LENGTH_LONG)
.show();
Intent intent = LoginActivity.Companion.newIntent(App.Companion.get());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
App.Companion.get().startActivity(intent);
}
});
}
return null;
}
}
package com.commit451.gitlab.api
import android.content.Intent
import android.widget.Toast
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.LoginActivity
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.util.ThreadUtil
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import timber.log.Timber
import java.io.IOException
/**
* If it detects a 401, redirect the user to the login screen, clearing activity the stack.
* Kinda a weird global way of forcing the user to the login screen if their auth has expired
*/
class OpenSignInAuthenticator(private val account: Account) : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route, response: Response): Request? {
//Special case for if someone just put in their username or password wrong
if ("session" != response.request().url().pathSegments()[response.request().url().pathSegments().size - 1]) {
//Off the background thread
Timber.wtf(RuntimeException("Got a 401 and showing sign in for url: " + response.request().url()))
ThreadUtil.postOnMainThread {
//Remove the account, so that the user can sign in again
App.get().prefs.removeAccount(account)
Toast.makeText(App.get(), R.string.error_401, Toast.LENGTH_LONG)
.show()
val intent = LoginActivity.newIntent(App.get())
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
App.get().startActivity(intent)
}
}
return null
}
}
package com.commit451.gitlab.api.converter;
package com.commit451.gitlab.api.converter
 
import android.net.Uri;
import android.net.Uri
 
import com.bluelinelabs.logansquare.typeconverters.StringBasedTypeConverter;
import com.bluelinelabs.logansquare.typeconverters.StringBasedTypeConverter
 
/**
* Simple Uri type converter
*/
public class UriTypeConverter extends StringBasedTypeConverter<Uri> {
class UriTypeConverter : StringBasedTypeConverter<Uri>() {
 
@Override
public String convertToString(Uri object) {
return object.toString();
override fun convertToString(`object`: Uri): String {
return `object`.toString()
}
 
@Override
public Uri getFromString(String string) {
override fun getFromString(string: String?): Uri? {
if (string != null) {
return Uri.parse(string);
return Uri.parse(string)
} else {
return null;
return null
}
}
}
package com.commit451.gitlab.api.rss;
import com.commit451.gitlab.util.ConversionUtil;
import org.simpleframework.xml.transform.Transform;
import java.util.Date;
/**
* Transforms dates!
*/
public class DateTransform implements Transform<Date> {
public DateTransform() {
}
@Override
public Date read(String value) throws Exception {
return ConversionUtil.toDate(value);
}
@Override
public String write(Date value) throws Exception {
return ConversionUtil.fromDate(value);
}
}
package com.commit451.gitlab.api.rss
import com.commit451.gitlab.util.ConversionUtil
import org.simpleframework.xml.transform.Transform
import java.util.*
/**
* Transforms dates!
*/
class DateTransform : Transform<Date> {
@Throws(Exception::class)
override fun read(value: String): Date {
return ConversionUtil.toDate(value)
}
@Throws(Exception::class)
override fun write(value: Date): String {
return ConversionUtil.fromDate(value)
}
}
package com.commit451.gitlab.api.rss;
import android.net.Uri;
import com.commit451.gitlab.model.Account;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;
import java.util.Date;
public final class SimpleXmlPersisterFactory {
public static Persister createPersister(final Account account) {
return new Persister(new Matcher() {
@Override
public Transform match(Class type) throws Exception {
if (Date.class.isAssignableFrom(type)) {
return new DateTransform();
} else if (Uri.class.isAssignableFrom(type)) {
return new UriTransform(account);
}
return null;
}
});
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment