From 3414d6b2868b1cfea10f4976e0303a145edb0aa3 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Wed, 25 Mar 2020 01:19:46 +0100 Subject: [PATCH 01/58] Split into two build flavours --- app/build.gradle | 38 +++- app/src/main/AndroidManifest.xml | 13 -- .../be/ugent/zeus/hydra/HydraApplication.java | 3 +- .../common/network/InstanceProvider.java | 24 +-- .../{Reporting.java => Manager.java} | 44 +---- .../ugent/zeus/hydra/feed/FeedViewModel.java | 2 +- .../hydra/onboarding/OnboardingActivity.java | 16 +- .../hydra/onboarding/ReportingFragment.java | 8 +- .../hydra/preferences/OverviewFragment.java | 8 + .../hydra/preferences/ReportingFragment.java | 3 +- app/src/open/AndroidManifest.xml | 9 + .../common/network/CertificateProvider.java | 13 ++ .../hydra/common/reporting/DummyHolder.java | 101 +++++++++++ .../hydra/common/reporting/DummyTracker.java | 46 +++++ .../hydra/common/reporting/Reporting.java | 47 +++++ .../resto/meta/RestoLocationActivity.java | 170 ++++++++++++++++++ .../res/layout/activity_resto_location.xml | 32 ++++ app/src/store/AndroidManifest.xml | 21 +++ app/{ => src/store}/google-services.json | 0 .../common/network/CertificateProvider.java | 30 ++++ .../common/reporting/FirebaseEvents.java | 0 .../common/reporting/FirebaseTracker.java | 0 .../hydra/common/reporting/Reporting.java | 43 +++++ .../resto/meta/RestoLocationActivity.java | 0 .../res/layout/activity_resto_location.xml | 5 +- .../java/be/ugent/zeus/hydra/TestApp.java | 8 +- 26 files changed, 581 insertions(+), 103 deletions(-) rename app/src/main/java/be/ugent/zeus/hydra/common/reporting/{Reporting.java => Manager.java} (66%) create mode 100644 app/src/open/AndroidManifest.xml create mode 100644 app/src/open/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java create mode 100644 app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyHolder.java create mode 100644 app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyTracker.java create mode 100644 app/src/open/java/be/ugent/zeus/hydra/common/reporting/Reporting.java create mode 100644 app/src/open/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java create mode 100644 app/src/open/res/layout/activity_resto_location.xml create mode 100644 app/src/store/AndroidManifest.xml rename app/{ => src/store}/google-services.json (100%) create mode 100644 app/src/store/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java rename app/src/{main => store}/java/be/ugent/zeus/hydra/common/reporting/FirebaseEvents.java (100%) rename app/src/{main => store}/java/be/ugent/zeus/hydra/common/reporting/FirebaseTracker.java (100%) create mode 100644 app/src/store/java/be/ugent/zeus/hydra/common/reporting/Reporting.java rename app/src/{main => store}/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java (100%) rename app/src/{main => store}/res/layout/activity_resto_location.xml (95%) diff --git a/app/build.gradle b/app/build.gradle index d14138ce0..6d4a05a44 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -22,9 +22,6 @@ android { vectorDrawables.useSupportLibrary = true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - manifestPlaceholders = [ - google_maps_key: props.getProperty('MAPS_API_KEY'), - ] // For a description of what these do, see the config.properties file. buildConfigField "boolean", "DEBUG_HOME_STREAM_PRIORITY", props.getProperty('hydra.debug.home.stream.priority') buildConfigField "boolean", "DEBUG_HOME_STREAM_STALL", props.getProperty('hydra.debug.home.stream.stall') @@ -42,6 +39,23 @@ android { } } + flavorDimensions "distribution" + + productFlavors { + + // Play Store and officially supported version + store { + manifestPlaceholders = [ + google_maps_key: props.getProperty('MAPS_API_KEY'), + ] + } + + open { + versionNameSuffix "-open" + applicationIdSuffix ".open" + } + } + // used by Room, to test migrations sourceSets { test.resources.srcDirs += files("$projectDir/schemas".toString()) @@ -123,9 +137,14 @@ dependencies { implementation 'com.jonathanfinerty.once:once:1.3.0' implementation 'blue.aodev:material-values:1.1.1' implementation 'com.google.android.gms:play-services-oss-licenses:17.0.0' - implementation 'com.google.android.gms:play-services-maps:17.0.0' - implementation 'com.google.firebase:firebase-analytics:17.2.3' - implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1' + + // Dependencies for the Play Store version. + storeImplementation 'com.google.android.gms:play-services-maps:17.0.0' + storeImplementation 'com.google.firebase:firebase-analytics:17.2.3' + storeImplementation 'com.crashlytics.sdk.android:crashlytics:2.10.1' + + // Dependencies for open version. + openImplementation 'org.osmdroid:osmdroid-android:6.1.6' if (props.getProperty("hydra.debug.leaks").toBoolean()) { logger.info("Leak tracking enabled...") @@ -160,6 +179,13 @@ dependencies { apply plugin: 'com.google.gms.google-services' + +// Disable Google services for open variant. +android.applicationVariants.all { variant -> + def googleTask = tasks.findByName("process${variant.name.capitalize()}GoogleServices") + googleTask.enabled = "open" != variant.flavorName +} + /** * Loads the default properties, and the user properties. This will also load the * secret keys. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1b0ecfc6f..86a3f0d19 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -27,19 +27,6 @@ android:networkSecurityConfig="@xml/network_security_config" tools:ignore="AllowBackup,GoogleAppIndexingWarning,UnusedAttribute"> - - - - - - - + + + + + + + diff --git a/app/src/open/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java b/app/src/open/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java new file mode 100644 index 000000000..64c2a2a1d --- /dev/null +++ b/app/src/open/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java @@ -0,0 +1,13 @@ +package be.ugent.zeus.hydra.common.network; + +import android.content.Context; + +/** + * @author Niko Strijbol + */ +public class CertificateProvider { + + public static void installProvider(Context context) { + // Nothing. + } +} diff --git a/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyHolder.java b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyHolder.java new file mode 100644 index 000000000..be05604ab --- /dev/null +++ b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyHolder.java @@ -0,0 +1,101 @@ +package be.ugent.zeus.hydra.common.reporting; + +/** + * @author Niko Strijbol + */ +class DummyHolder implements BaseEvents { + + private static class DummyParams implements Params { + + @Override + public String method() { + return "null"; + } + + @Override + public String searchTerm() { + return "null"; + } + + @Override + public String contentType() { + return "null"; + } + + @Override + public String itemId() { + return "null"; + } + + @Override + public String itemName() { + return "null"; + } + + @Override + public String itemCategory() { + return "null"; + } + + @Override + public String dismissalType() { + return "null"; + } + + @Override + public String cardType() { + return "null"; + } + + @Override + public String cardIdentifier() { + return "null"; + } + } + + + @Override + public Params params() { + return new DummyParams(); + } + + @Override + public String login() { + return "null"; + } + + @Override + public String search() { + return "null"; + } + + @Override + public String selectContent() { + return "null"; + } + + @Override + public String share() { + return "null"; + } + + @Override + public String tutorialBegin() { + return "null"; + } + + @Override + public String tutorialComplete() { + return "null"; + } + + @Override + public String viewItem() { + return "null"; + } + + @Override + public String cardDismissal() { + return "null"; + } +} diff --git a/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyTracker.java b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyTracker.java new file mode 100644 index 000000000..44dec599b --- /dev/null +++ b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/DummyTracker.java @@ -0,0 +1,46 @@ +package be.ugent.zeus.hydra.common.reporting; + +import android.app.Activity; +import androidx.annotation.NonNull; + +/** + * Tracker that does nothing. + * + * @author Niko Strijbol + */ +class DummyTracker implements Tracker { + @Override + public void log(Event event) { + // Nothing. + } + + @Override + public void setCurrentScreen(@NonNull Activity activity, String screenName, String classOverride) { + // Nothing. + } + + @Override + public void setUserProperty(String name, String value) { + // Nothing. + } + + @Override + public void logError(Throwable throwable) { + // Nothing. + } + + @Override + public void logErrorMessage(String message) { + // Nothing. + } + + @Override + public void allowAnalytics(boolean allowed) { + // Nothing. + } + + @Override + public void allowCrashReporting(boolean allowed) { + // Nothing. + } +} diff --git a/app/src/open/java/be/ugent/zeus/hydra/common/reporting/Reporting.java b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/Reporting.java new file mode 100644 index 000000000..abebfb507 --- /dev/null +++ b/app/src/open/java/be/ugent/zeus/hydra/common/reporting/Reporting.java @@ -0,0 +1,47 @@ +package be.ugent.zeus.hydra.common.reporting; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; +import androidx.annotation.VisibleForTesting; +import androidx.preference.PreferenceManager; +import be.ugent.zeus.hydra.BuildConfig; + +/** + * Produces the default tracker. + * + * @author Niko Strijbol + */ +public final class Reporting { + + private static Tracker tracker; + private final static Object lock = new Object(); + + /** + * Get the default tracker. + * + * @param context The context. + * @return The tracker. + */ + public static Tracker getTracker(Context context) { + synchronized (lock) { + if (tracker == null) { + tracker = new DummyTracker(); + } + } + return tracker; + } + + public static BaseEvents getEvents() { + return new DummyHolder(); + } + + @VisibleForTesting + public static void setTracker(Tracker tracker) { + Reporting.tracker = tracker; + } + + public static boolean hasReportingOptions() { + return false; + } +} diff --git a/app/src/open/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java b/app/src/open/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java new file mode 100644 index 000000000..6dfd0c966 --- /dev/null +++ b/app/src/open/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java @@ -0,0 +1,170 @@ +package be.ugent.zeus.hydra.resto.meta; + +import android.Manifest; +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.ProgressBar; +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.lifecycle.ViewModelProvider; +import androidx.preference.PreferenceManager; + +import be.ugent.zeus.hydra.R; +import be.ugent.zeus.hydra.common.arch.observers.PartialErrorObserver; +import be.ugent.zeus.hydra.common.arch.observers.ProgressObserver; +import be.ugent.zeus.hydra.common.arch.observers.SuccessObserver; +import be.ugent.zeus.hydra.common.ui.BaseActivity; +import com.google.android.material.snackbar.Snackbar; +import org.osmdroid.api.IMapController; +import org.osmdroid.config.Configuration; +import org.osmdroid.tileprovider.tilesource.TileSourceFactory; +import org.osmdroid.util.GeoPoint; +import org.osmdroid.views.CustomZoomButtonsController; +import org.osmdroid.views.MapView; +import org.osmdroid.views.overlay.Marker; +import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; +import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; + +public class RestoLocationActivity extends BaseActivity { + + private static final String TAG = "RestoLocationActivity"; + + private static final GeoPoint DEFAULT_LOCATION = new GeoPoint(51.05, 3.72); //Gent + private static final float DEFAULT_ZOOM = 15; + + private static final int MY_LOCATION_REQUEST_CODE = 1; + + private MapView map; + private RestoMeta meta; + private ProgressBar progressBar; + private MetaViewModel viewModel; + + private MyLocationNewOverlay myLocation; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + Context ctx = getApplicationContext(); + Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); + + setContentView(R.layout.activity_resto_location); + + progressBar = findViewById(R.id.progress_bar); + map = findViewById(R.id.map); + map.setTileSource(TileSourceFactory.MAPNIK); + map.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.ALWAYS); + map.setMultiTouchControls(true); + + IMapController mapController = map.getController(); + mapController.setZoom(DEFAULT_ZOOM); + mapController.setCenter(DEFAULT_LOCATION); + + viewModel = new ViewModelProvider(this).get(MetaViewModel.class); + viewModel.getData().observe(this, PartialErrorObserver.with(this::onError)); + viewModel.getData().observe(this, new ProgressObserver<>(progressBar)); + viewModel.getData().observe(this, SuccessObserver.with(this::receiveData)); + + if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + enableLocation(); + } else { + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE); + } + } + + private void receiveData(@NonNull RestoMeta data) { + meta = data; + if (map != null) { + addData(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_resto_location, menu); + tintToolbarIcons(menu, R.id.resto_refresh, R.id.resto_center); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.resto_refresh: + viewModel.onRefresh(); + return true; + case R.id.resto_center: + if (this.myLocation != null) { + IMapController mapController = map.getController(); + mapController.setCenter(myLocation.getMyLocation()); + } + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + private void addData() { + + for (Resto location : meta.locations) { + GeoPoint point = new GeoPoint(location.getLatitude(), location.getLongitude()); + Marker m = new Marker(map); + m.setPosition(point); + m.setTitle(location.getName()); + m.setSubDescription(location.getAddress()); + m.setDraggable(false); + map.getOverlayManager().add(m); + } + progressBar.setVisibility(View.GONE); + } + + @Override + @SuppressWarnings("MissingPermission") + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + + //The map should never be null, but check anyway + if (map == null) { + return; + } + + if (requestCode == MY_LOCATION_REQUEST_CODE) { + if (permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + enableLocation(); + } + } + } + + private void enableLocation() { + if (myLocation != null) { + myLocation.disableMyLocation(); + map.getOverlayManager().remove(myLocation); + } + myLocation = new MyLocationNewOverlay(new GpsMyLocationProvider(this), map); + myLocation.enableMyLocation(); + map.getOverlayManager().add(myLocation); + } + + private void onError(Throwable throwable) { + Log.e(TAG, "Error while getting data.", throwable); + Snackbar.make(findViewById(android.R.id.content), getString(R.string.error_network), Snackbar.LENGTH_LONG) + .setAction(getString(R.string.action_again), v -> viewModel.onRefresh()) + .show(); + } + + @Override + protected void onResume() { + super.onResume(); + map.onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + map.onPause(); + } +} diff --git a/app/src/open/res/layout/activity_resto_location.xml b/app/src/open/res/layout/activity_resto_location.xml new file mode 100644 index 000000000..286286831 --- /dev/null +++ b/app/src/open/res/layout/activity_resto_location.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/store/AndroidManifest.xml b/app/src/store/AndroidManifest.xml new file mode 100644 index 000000000..e5f5fae7a --- /dev/null +++ b/app/src/store/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + diff --git a/app/google-services.json b/app/src/store/google-services.json similarity index 100% rename from app/google-services.json rename to app/src/store/google-services.json diff --git a/app/src/store/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java b/app/src/store/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java new file mode 100644 index 000000000..0ee6a881f --- /dev/null +++ b/app/src/store/java/be/ugent/zeus/hydra/common/network/CertificateProvider.java @@ -0,0 +1,30 @@ +package be.ugent.zeus.hydra.common.network; + +import android.content.Context; +import android.util.Log; + +import com.google.android.gms.common.GoogleApiAvailability; +import com.google.android.gms.common.GooglePlayServicesNotAvailableException; +import com.google.android.gms.common.GooglePlayServicesRepairableException; +import com.google.android.gms.security.ProviderInstaller; + +/** + * @author Niko Strijbol + */ +public class CertificateProvider { + + private static final String TAG = "CertificateProvider"; + + public static void installProvider(Context context) { + Log.i(TAG, "Installing Play Services to enable TLSv1.2"); + try { + ProviderInstaller.installIfNeeded(context); + } catch (GooglePlayServicesRepairableException e) { + Log.w(TAG, "Play Services are outdated", e); + // Prompt the user to install/update/enable Google Play services. + GoogleApiAvailability.getInstance().showErrorNotification(context, e.getConnectionStatusCode()); + } catch (GooglePlayServicesNotAvailableException e) { + Log.e(TAG, "Unable to install provider, SSL will not work", e); + } + } +} diff --git a/app/src/main/java/be/ugent/zeus/hydra/common/reporting/FirebaseEvents.java b/app/src/store/java/be/ugent/zeus/hydra/common/reporting/FirebaseEvents.java similarity index 100% rename from app/src/main/java/be/ugent/zeus/hydra/common/reporting/FirebaseEvents.java rename to app/src/store/java/be/ugent/zeus/hydra/common/reporting/FirebaseEvents.java diff --git a/app/src/main/java/be/ugent/zeus/hydra/common/reporting/FirebaseTracker.java b/app/src/store/java/be/ugent/zeus/hydra/common/reporting/FirebaseTracker.java similarity index 100% rename from app/src/main/java/be/ugent/zeus/hydra/common/reporting/FirebaseTracker.java rename to app/src/store/java/be/ugent/zeus/hydra/common/reporting/FirebaseTracker.java diff --git a/app/src/store/java/be/ugent/zeus/hydra/common/reporting/Reporting.java b/app/src/store/java/be/ugent/zeus/hydra/common/reporting/Reporting.java new file mode 100644 index 000000000..6c49f8208 --- /dev/null +++ b/app/src/store/java/be/ugent/zeus/hydra/common/reporting/Reporting.java @@ -0,0 +1,43 @@ +package be.ugent.zeus.hydra.common.reporting; + +import android.content.Context; +import androidx.annotation.VisibleForTesting; + +/** + * Produces the default tracker. + * + * @author Niko Strijbol + */ +public final class Reporting { + + private static Tracker tracker; + private final static Object lock = new Object(); + + /** + * Get the default tracker. + * + * @param context The context. + * @return The tracker. + */ + public static Tracker getTracker(Context context) { + synchronized (lock) { + if (tracker == null) { + tracker = new FirebaseTracker(context); + } + } + return tracker; + } + + public static BaseEvents getEvents() { + return FirebaseEvents.getInstance(); + } + + @VisibleForTesting + public static void setTracker(Tracker tracker) { + Reporting.tracker = tracker; + } + + public static boolean hasReportingOptions() { + return true; + } +} diff --git a/app/src/main/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java b/app/src/store/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java similarity index 100% rename from app/src/main/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java rename to app/src/store/java/be/ugent/zeus/hydra/resto/meta/RestoLocationActivity.java diff --git a/app/src/main/res/layout/activity_resto_location.xml b/app/src/store/res/layout/activity_resto_location.xml similarity index 95% rename from app/src/main/res/layout/activity_resto_location.xml rename to app/src/store/res/layout/activity_resto_location.xml index e11c2aa80..70e14abae 100644 --- a/app/src/main/res/layout/activity_resto_location.xml +++ b/app/src/store/res/layout/activity_resto_location.xml @@ -19,10 +19,9 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:animateLayoutChanges="true" - app:layout_behavior="@string/appbar_scrolling_view_behavior" - > + app:layout_behavior="@string/appbar_scrolling_view_behavior"> - Date: Mon, 30 Mar 2020 12:41:35 +0200 Subject: [PATCH 02/58] Use our own fork of the license plugin --- app/build.gradle | 3 +- .../zeus/hydra/preferences/AboutFragment.java | 9 +- build.gradle | 1 - buildSrc/README.md | 6 + buildSrc/build.gradle | 18 ++ .../zeus/hydra/licenses/ArtifactInfo.groovy | 50 ++++ .../zeus/hydra/licenses/DependencyTask.groovy | 237 +++++++++++++++ .../hydra/licenses/GenerateLicense.groovy | 18 ++ .../hydra/licenses/LicensesCleanUpTask.groovy | 58 ++++ .../zeus/hydra/licenses/LicensesTask.groovy | 273 ++++++++++++++++++ .../hydra/licenses/OssLicensesPlugin.groovy | 83 ++++++ .../be.ugent.zeus.hydra.licenses.properties | 1 + 12 files changed, 750 insertions(+), 7 deletions(-) create mode 100644 buildSrc/README.md create mode 100644 buildSrc/build.gradle create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/ArtifactInfo.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesCleanUpTask.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy create mode 100644 buildSrc/src/main/resources/META-INF/gradle-plugins/be.ugent.zeus.hydra.licenses.properties diff --git a/app/build.gradle b/app/build.gradle index 6d4a05a44..f12338514 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,5 +1,5 @@ apply plugin: 'com.android.application' -apply plugin: 'com.google.android.gms.oss-licenses-plugin' +apply plugin: 'be.ugent.zeus.hydra.licenses' apply plugin: 'io.fabric' // Read our properties, see bottom for details. @@ -136,7 +136,6 @@ dependencies { implementation 'com.heinrichreimersoftware:material-intro:2.0.0' implementation 'com.jonathanfinerty.once:once:1.3.0' implementation 'blue.aodev:material-values:1.1.1' - implementation 'com.google.android.gms:play-services-oss-licenses:17.0.0' // Dependencies for the Play Store version. storeImplementation 'com.google.android.gms:play-services-maps:17.0.0' diff --git a/app/src/main/java/be/ugent/zeus/hydra/preferences/AboutFragment.java b/app/src/main/java/be/ugent/zeus/hydra/preferences/AboutFragment.java index 2eb7b7d3e..6830574f2 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/preferences/AboutFragment.java +++ b/app/src/main/java/be/ugent/zeus/hydra/preferences/AboutFragment.java @@ -3,7 +3,6 @@ import android.content.Intent; import android.os.Build; import android.os.Bundle; - import androidx.appcompat.content.res.AppCompatResources; import androidx.preference.Preference; @@ -11,7 +10,7 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.PreferenceFragment; -import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; +import be.ugent.zeus.hydra.common.ui.WebViewActivity; /** * @author Niko Strijbol @@ -32,8 +31,10 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { )); requirePreference("pref_about_licenses").setOnPreferenceClickListener(preference -> { - OssLicensesMenuActivity.setActivityTitle(getString(R.string.pref_licenses_title)); - startActivity(new Intent(getActivity(), OssLicensesMenuActivity.class)); + Intent intent = new Intent(requireActivity(), WebViewActivity.class); + intent.putExtra(WebViewActivity.TITLE, getString(R.string.pref_licenses_title)); + intent.putExtra(WebViewActivity.URL, "file:///android_res/raw/third_party_licenses.html"); + startActivity(intent); return false; }); diff --git a/build.gradle b/build.gradle index cce789308..c00212074 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,6 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:3.6.1' classpath 'com.google.gms:google-services:4.3.3' - classpath 'com.google.android.gms:oss-licenses-plugin:0.10.2' classpath 'io.fabric.tools:gradle:1.31.2' } } diff --git a/buildSrc/README.md b/buildSrc/README.md new file mode 100644 index 000000000..230c82d32 --- /dev/null +++ b/buildSrc/README.md @@ -0,0 +1,6 @@ +# License plugin + +This plugin will collect licences of dependencies. +It is a fork of https://github.com/google/play-services-plugins/tree/master/oss-licenses-plugin, where the output is not some weird format, but an HTML file. + +The fork is based on version oss-licenses-plugin-v0.10.2 \ No newline at end of file diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 000000000..71b6d15e1 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'groovy' + id 'java' + id 'idea' +} + +repositories { + google() + jcenter() +} + +dependencies { + implementation gradleApi() + implementation localGroovy() + implementation 'com.android.tools.build:gradle:3.6.1' + testImplementation 'junit:junit:4.13' + testImplementation 'org.mockito:mockito-core:3.2.4' +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/ArtifactInfo.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/ArtifactInfo.groovy new file mode 100644 index 000000000..b6dc3106a --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/ArtifactInfo.groovy @@ -0,0 +1,50 @@ +/** + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses + +class ArtifactInfo { + private String group + private String name + private String fileLocation + private String version + + ArtifactInfo(String group, + String name, + String fileLocation, + String version) { + this.group = group + this.name = name + this.fileLocation = fileLocation + this.version = version + } + + String getGroup() { + return group + } + + String getName() { + return name + } + + String getFileLocation() { + return fileLocation + } + + String getVersion() { + return version + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy new file mode 100644 index 000000000..4b5da076f --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy @@ -0,0 +1,237 @@ +/** + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses + +import groovy.json.JsonBuilder +import groovy.json.JsonException +import groovy.json.JsonSlurper +import org.gradle.api.DefaultTask +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.ConfigurationContainer +import org.gradle.api.artifacts.ResolveException +import org.gradle.api.artifacts.ResolvedArtifact +import org.gradle.api.artifacts.ResolvedDependency +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction +import org.gradle.internal.component.AmbiguousVariantSelectionException +import org.slf4j.LoggerFactory + +/** + * This task does the following: + * First it finds all dependencies that meet all the requirements below: + * 1. Can be resolved. + * 2. Not test compile. + * Then it finds all the artifacts associated with the dependencies. + * Finally it generates a json file that contains the information about these + * artifacts. + */ +class DependencyTask extends DefaultTask { + protected Set artifactSet = [] + protected Set artifactInfos = [] + protected static final String LOCAL_LIBRARY_VERSION = "unspecified" + private static final String TEST_PREFIX = "test" + private static final String ANDROID_TEST_PREFIX = "androidTest" + private static final Set TEST_COMPILE = ["testCompile", + "androidTestCompile"] + + private static final Set PACKAGED_DEPENDENCIES_PREFIXES = ["compile", + "implementation", + "api"] + + private static final logger = LoggerFactory.getLogger(DependencyTask.class) + + @Input + public ConfigurationContainer configurations + + @OutputDirectory + public File outputDir + + @OutputFile + public File outputFile + + @TaskAction + void action() { + initOutput() + updateDependencyArtifacts() + + if (outputFile.exists() && checkArtifactSet(outputFile)) { + return + } + + outputFile.newWriter() + outputFile.write(new JsonBuilder(artifactInfos).toPrettyString()) + } + + /** + * Checks if current artifact set is the same as the artifact set in the + * json file + * @param file + * @return true if artifactSet is the same as the json file, + * false otherwise + */ + protected boolean checkArtifactSet(File file) { + try { + def previousArtifacts = new JsonSlurper().parse(file) + for (entry in previousArtifacts) { + String key = "${entry.fileLocation}" + if (artifactSet.contains(key)) { + artifactSet.remove(key) + } else { + return false + } + } + return artifactSet.isEmpty() + } catch (JsonException ignored) { + return false + } + } + + protected void updateDependencyArtifacts() { + for (Configuration configuration : configurations) { + Set artifacts = getResolvedArtifacts( + configuration) + if (artifacts == null) { + continue + } + + addArtifacts(artifacts) + } + } + + protected addArtifacts(Set artifacts) { + for (ResolvedArtifact artifact : artifacts) { + String group = artifact.moduleVersion.id.group + String artifact_key = artifact.file.getAbsolutePath() + + if (artifactSet.contains(artifact_key)) { + continue + } + + artifactSet.add(artifact_key) + artifactInfos.add(new ArtifactInfo(group, artifact.name, + artifact.file.getAbsolutePath(), + artifact.moduleVersion.id.version)) + } + } + + /** + * Checks if the configuration can be resolved. isCanBeResolved is added to + * gradle Api since 3.3. For the previous version, all the configurations + * can be resolved. + * @param configuration + * @return true if configuration can be resolved or the api is lower than + * 3.3, otherwise false. + */ + protected boolean canBeResolved(Configuration configuration) { + return configuration.metaClass.respondsTo(configuration, + "isCanBeResolved") ? configuration.isCanBeResolved() : true + } + + /** + * Checks if the configuration is from test. + * @param configuration + * @return true if configuration is a test configuration or its parent + * configurations are either testCompile or androidTestCompile, otherwise + * false. + */ + protected boolean isTest(Configuration configuration) { + boolean isTestConfiguration = ( + configuration.name.startsWith(TEST_PREFIX) || + configuration.name.startsWith(ANDROID_TEST_PREFIX)) + configuration.hierarchy.each { + isTestConfiguration |= TEST_COMPILE.contains(it.name) + } + return isTestConfiguration + } + + /** + * Checks if the configuration is for a packaged dependency (rather than e.g. a build or test time dependency) + * @param configuration + * @return true if the configuration is in the set of @link #BINARY_DEPENDENCIES + */ + protected boolean isPackagedDependency(Configuration configuration) { + boolean isPackagedDependency = PACKAGED_DEPENDENCIES_PREFIXES.any { + configuration.name.startsWith(it) + } + configuration.hierarchy.each { + String configurationHierarchyName = it.name + isPackagedDependency |= PACKAGED_DEPENDENCIES_PREFIXES.any { + configurationHierarchyName.startsWith(it) + } + } + + return isPackagedDependency + } + + protected Set getResolvedArtifacts( + Configuration configuration) { + /** + * skip the configurations that, cannot be resolved in + * newer version of gradle api, are tests, or are not packaged dependencies. + */ + + if (!canBeResolved(configuration) + || isTest(configuration) + || !isPackagedDependency(configuration)) { + return null + } + + try { + return getResolvedArtifactsFromResolvedDependencies( + configuration.getResolvedConfiguration() + .getLenientConfiguration() + .getFirstLevelModuleDependencies()) + } catch (ResolveException exception) { + logger.warn("Failed to resolve OSS licenses for $configuration.name.", exception) + return null + } + } + + protected Set getResolvedArtifactsFromResolvedDependencies( + Set resolvedDependencies) { + + HashSet resolvedArtifacts = new HashSet<>() + for (resolvedDependency in resolvedDependencies) { + try { + if (resolvedDependency.getModuleVersion() == LOCAL_LIBRARY_VERSION) { + /** + * Attempting to getAllModuleArtifacts on a local library project will result + * in AmbiguousVariantSelectionException as there are not enough criteria + * to match a specific variant of the library project. Instead we skip the + * the library project itself and enumerate its dependencies. + */ + resolvedArtifacts.addAll( + getResolvedArtifactsFromResolvedDependencies( + resolvedDependency.getChildren())) + } else { + resolvedArtifacts.addAll(resolvedDependency.getAllModuleArtifacts()) + } + } catch (AmbiguousVariantSelectionException exception) { + logger.warn("Failed to process $resolvedDependency.name", exception) + } + } + return resolvedArtifacts + } + + private void initOutput() { + if (!outputDir.exists()) { + outputDir.mkdirs() + } + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy new file mode 100644 index 000000000..691bac214 --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy @@ -0,0 +1,18 @@ +package be.ugent.zeus.hydra.licenses + +import org.gradle.api.DefaultTask +import org.gradle.api.tasks.TaskAction + +/** + * @author Niko Strijbol + */ +class GenerateLicense extends DefaultTask { + + @TaskAction + def generate() { + + + + } + +} diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesCleanUpTask.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesCleanUpTask.groovy new file mode 100644 index 000000000..fa4c16246 --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesCleanUpTask.groovy @@ -0,0 +1,58 @@ +/** + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses + +import org.gradle.api.DefaultTask +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction + +/** + * Task to clean up the generated dependency.json, third_party_licenses and + * third_party_license_metadata files. + */ +class LicensesCleanUpTask extends DefaultTask { + @Input + public File dependencyFile + + @Input + public File dependencyDir + + @Input + public File htmlFile + + @Input + public File licensesDir + + @TaskAction + void action() { + if (dependencyFile.exists()) { + dependencyFile.delete() + } + + if (dependencyDir.isDirectory() && dependencyDir.list().length == 0) { + dependencyDir.delete() + } + + if (htmlFile.exists()) { + htmlFile.delete() + } + + if (licensesDir.isDirectory() && licensesDir.list().length == 0) { + licensesDir.delete() + } + } +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy new file mode 100644 index 000000000..85d7324cc --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy @@ -0,0 +1,273 @@ +/** + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses + +import groovy.json.JsonSlurper +import groovy.xml.MarkupBuilder +import org.gradle.api.DefaultTask +import org.gradle.api.artifacts.component.ModuleComponentIdentifier +import org.gradle.api.artifacts.result.ResolvedArtifactResult +import org.gradle.api.internal.artifacts.DefaultModuleIdentifier +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction +import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier +import org.gradle.maven.MavenModule +import org.gradle.maven.MavenPomArtifact +import org.slf4j.LoggerFactory + +import java.util.zip.ZipEntry +import java.util.zip.ZipFile + +/** + * Task to find available licenses from the artifacts stored in the json + * file generated by DependencyTask, and then generate the third_party_licenses + * and third_party_license_metadata file. + */ +class LicensesTask extends DefaultTask { + private static final String UTF_8 = "UTF-8" + private static final int GRANULAR_BASE_VERSION = 14 + private static final String GOOGLE_PLAY_SERVICES_GROUP = + "com.google.android.gms" + private static final String LICENSE_ARTIFACT_SURFIX = "-license" + private static final String FIREBASE_GROUP = "com.google.firebase" + private static final String FAIL_READING_LICENSES_ERROR = + "Failed to read license text." + + private static final logger = LoggerFactory.getLogger(LicensesTask.class) + + protected Set googleServiceLicenses = [] + protected Map licensesMap = [:] + + @InputFile + public File dependenciesJson + + @OutputDirectory + public File outputDir + + @OutputFile + public File html + + @TaskAction + void action() { + initOutputDir() + initLicenseFile() + + def allDependencies = new JsonSlurper().parse(dependenciesJson) + for (entry in allDependencies) { + String group = entry.group + String name = entry.name + String fileLocation = entry.fileLocation + String version = entry.version + File artifactLocation = new File(fileLocation) + + if (isGoogleServices(group)) { + // Add license info for google-play-services itself + if (!name.endsWith(LICENSE_ARTIFACT_SURFIX)) { + addLicensesFromPom(group, name, version) + } + // Add transitive licenses info for google-play-services. For + // post-granular versions, this is located in the artifact + // itself, whereas for pre-granular versions, this information + // is located at the complementary license artifact as a runtime + // dependency. + if (isGranularVersion(version)) { + addGooglePlayServiceLicenses(artifactLocation) + } else if (name.endsWith(LICENSE_ARTIFACT_SURFIX)) { + addGooglePlayServiceLicenses(artifactLocation) + } + } else { + addLicensesFromPom(group, name, version) + } + } + + writeMetadata() + } + + protected void initOutputDir() { + if (!outputDir.exists()) { + outputDir.mkdirs() + } + } + + protected void initLicenseFile() { + if (html == null) { + logger.error("License file is undefined") + } + html.newWriter().withWriter { w -> + w << '' + } + } + + protected static boolean isGoogleServices(String group) { + return (GOOGLE_PLAY_SERVICES_GROUP.equalsIgnoreCase(group) + || FIREBASE_GROUP.equalsIgnoreCase(group)) + } + + protected static boolean isGranularVersion(String version) { + String[] versions = version.split("\\.") + return (versions.length > 0 + && Integer.valueOf(versions[0]) >= GRANULAR_BASE_VERSION) + } + + protected void addGooglePlayServiceLicenses(File artifactFile) { + ZipFile licensesZip = new ZipFile(artifactFile) + JsonSlurper jsonSlurper = new JsonSlurper() + + ZipEntry jsonFile = licensesZip.getEntry("third_party_licenses.json") + ZipEntry txtFile = licensesZip.getEntry("third_party_licenses.txt") + + if (!jsonFile || !txtFile) { + return + } + + Object licensesObj = jsonSlurper.parse(licensesZip.getInputStream( + jsonFile)) + if (licensesObj == null) { + return + } + + for (entry in licensesObj) { + String key = entry.key + int startValue = entry.value.start + int lengthValue = entry.value.length + + if (!googleServiceLicenses.contains(key)) { + googleServiceLicenses.add(key) + byte[] content = getBytesFromInputStream( + licensesZip.getInputStream(txtFile), + startValue, + lengthValue) + appendLicense(key, content) + } + } + } + + protected static byte[] getBytesFromInputStream( + InputStream stream, + long offset, + int length) { + try { + byte[] buffer = new byte[1024] + ByteArrayOutputStream textArray = new ByteArrayOutputStream() + + stream.skip(offset) + int bytesRemaining = length > 0 ? length : Integer.MAX_VALUE + int bytes = 0 + + while (bytesRemaining > 0 && (bytes = stream.read(buffer, 0, Math.min(bytesRemaining, buffer.length))) != -1) { + textArray.write(buffer, 0, bytes) + bytesRemaining -= bytes + } + stream.close() + + return textArray.toByteArray() + } catch (Exception e) { + throw new RuntimeException(FAIL_READING_LICENSES_ERROR, e) + } + } + + protected void addLicensesFromPom(String group, String name, String version) { + def pomFile = resolvePomFileArtifact(group, name, version) + addLicensesFromPom((File) pomFile, group, name) + } + + protected void addLicensesFromPom(File pomFile, String group, String name) { + if (pomFile == null || !pomFile.exists()) { + logger.error("POM file $pomFile for $group:$name does not exist.") + return + } + + def rootNode = new XmlSlurper().parse(pomFile) + if (rootNode.licenses.size() == 0) { + return + } + + String licenseKey = "${group}:${name}" + if (rootNode.licenses.license.size() > 1) { + rootNode.licenses.license.each { node -> + String nodeName = node.name + String nodeUrl = node.url + appendLicense("${licenseKey} ${nodeName}", nodeUrl.getBytes(UTF_8)) + } + } else { + String nodeUrl = rootNode.licenses.license.url + appendLicense(licenseKey, nodeUrl.getBytes(UTF_8)) + } + } + + private File resolvePomFileArtifact(String group, String name, String version) { + def moduleComponentIdentifier = + createModuleComponentIdentifier(group, name, version) + logger.info("Resolving POM file for $moduleComponentIdentifier licenses.") + def components = getProject().getDependencies() + .createArtifactResolutionQuery() + .forComponents(moduleComponentIdentifier) + .withArtifacts(MavenModule.class, MavenPomArtifact.class) + .execute() + if (components.resolvedComponents.isEmpty()) { + logger.warn("$moduleComponentIdentifier has no POM file.") + return null + } + + def artifacts = components.resolvedComponents[0].getArtifacts(MavenPomArtifact.class) + if (artifacts.isEmpty()) { + logger.error("$moduleComponentIdentifier empty POM artifact list.") + return null + } + if (!(artifacts[0] instanceof ResolvedArtifactResult)) { + logger.error("$moduleComponentIdentifier unexpected type ${artifacts[0].class}") + return null + } + return ((ResolvedArtifactResult) artifacts[0]).getFile() + } + + protected void appendLicense(String key, byte[] content) { + if (licensesMap.containsKey(key)) { + return + } + + licensesMap.put(key, new String(content, UTF_8)) + } + + protected void writeMetadata() { + def html = new MarkupBuilder(html.newWriter(UTF_8)) + html.doubleQuotes = true + html.expandEmptyElements = true + html.omitEmptyAttributes = false + html.omitNullAttributes = false + html.html { + head { + title("Licenties") + } + body { + for (entry in licensesMap) { + details { + summary(entry.key) + pre(entry.value) + } + } + } + } + } + + private static ModuleComponentIdentifier createModuleComponentIdentifier(String group, String name, String version) { + return new DefaultModuleComponentIdentifier(DefaultModuleIdentifier.newId(group, name), version) + } + +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy new file mode 100644 index 000000000..af8f6ed45 --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy @@ -0,0 +1,83 @@ +/** + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses + +import com.android.build.gradle.api.BaseVariant +import org.gradle.api.Plugin +import org.gradle.api.Project + +class OssLicensesPlugin implements Plugin { + void apply(Project project) { + def getDependencies = project.tasks.create("getDependencies", DependencyTask) + def dependencyOutput = new File(project.buildDir, "generated/third_party_licenses") + def generatedJson = new File(dependencyOutput, "dependencies.json") + getDependencies.configurations = project.getConfigurations() + getDependencies.outputDir = dependencyOutput + getDependencies.outputFile = generatedJson + + def resourceOutput = new File(dependencyOutput, "/res") + def outputDir = new File(resourceOutput, "/raw") + def licensesFile = new File(outputDir, "third_party_licenses.html") + def licenseTask = project.tasks.create("generateLicenses", LicensesTask) + + licenseTask.dependenciesJson = generatedJson + licenseTask.outputDir = outputDir + licenseTask.html = licensesFile + + licenseTask.inputs.file(generatedJson) + licenseTask.outputs.dir(outputDir) + licenseTask.outputs.files(licensesFile) + + licenseTask.dependsOn(getDependencies) + + project.android.applicationVariants.all { BaseVariant variant -> + // This is necessary for backwards compatibility with versions of gradle that do not support + // this new API. + if (variant.hasProperty("preBuildProvider")) { + variant.preBuildProvider.configure { dependsOn(licenseTask) } + } else { + //noinspection GrDeprecatedAPIUsage + variant.preBuild.dependsOn(licenseTask) + } + + // This is necessary for backwards compatibility with versions of gradle that do not support + // this new API. + if (variant.respondsTo("registerGeneratedResFolders")) { + licenseTask.ext.generatedResFolders = project.files(resourceOutput).builtBy(licenseTask) + variant.registerGeneratedResFolders(licenseTask.generatedResFolders) + + if (variant.hasProperty("mergeResourcesProvider")) { + variant.mergeResourcesProvider.configure { dependsOn(licenseTask) } + } else { + //noinspection GrDeprecatedAPIUsage + variant.mergeResources.dependsOn(licenseTask) + } + } else { + //noinspection GrDeprecatedAPIUsage + variant.registerResGeneratingTask(licenseTask, resourceOutput) + } + } + + def cleanupTask = project.tasks.create("licensesCleanUp", LicensesCleanUpTask) + cleanupTask.dependencyFile = generatedJson + cleanupTask.dependencyDir = dependencyOutput + cleanupTask.htmlFile = licensesFile + cleanupTask.licensesDir = outputDir + + project.tasks.findByName("clean").dependsOn(cleanupTask) + } +} \ No newline at end of file diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/be.ugent.zeus.hydra.licenses.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/be.ugent.zeus.hydra.licenses.properties new file mode 100644 index 000000000..1cd39b971 --- /dev/null +++ b/buildSrc/src/main/resources/META-INF/gradle-plugins/be.ugent.zeus.hydra.licenses.properties @@ -0,0 +1 @@ +implementation-class=be.ugent.zeus.hydra.licenses.OssLicensesPlugin From 6bd728f9feee0d088ad08ebe9d9210b1df02a3b3 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:20:54 +0200 Subject: [PATCH 03/58] Use our own fork of the license plugin --- app/build.gradle | 2 +- .../zeus/hydra/licenses/DependencyTask.groovy | 28 +- .../hydra/licenses/GenerateLicense.groovy | 18 - .../zeus/hydra/licenses/LicenseMap.groovy | 68 +++ .../zeus/hydra/licenses/LicensesTask.groovy | 49 ++- .../hydra/licenses/OssLicensesPlugin.groovy | 35 +- .../main/resources/license/android-terms.txt | 161 +++++++ .../src/main/resources/license/apache-2.0.txt | 176 ++++++++ .../src/main/resources/license/gplv2ce.txt | 349 +++++++++++++++ .../main/resources/license/material-intro.txt | 21 + .../src/main/resources/license/threeten.txt | 29 ++ .../hydra/licenses/DependencyTaskTest.java | 413 ++++++++++++++++++ .../licenses/GoogleServicesLicenseTest.java | 68 +++ .../licenses/LicensesCleanUpTaskTest.java | 65 +++ .../zeus/hydra/licenses/LicensesTaskTest.java | 270 ++++++++++++ .../resources/dependencies/groupA/deps1.pom | 16 + .../resources/dependencies/groupA/deps1.txt | 1 + .../dependencies/groupB/abc/deps2.txt | 1 + .../dependencies/groupB/bcd/deps2.pom | 16 + .../resources/dependencies/groupC/deps3.txt | 1 + .../resources/dependencies/groupD/deps4.txt | 1 + .../resources/dependencies/groupE/deps5.pom | 20 + .../resources/dependencies/groupE/deps5.txt | 1 + .../sampleLicenses/third_party_licenses.json | 1 + .../sampleLicenses/third_party_licenses.txt | 1 + .../src/test/resources/testDependency.json | 26 ++ 26 files changed, 1791 insertions(+), 46 deletions(-) delete mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy create mode 100644 buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicenseMap.groovy create mode 100644 buildSrc/src/main/resources/license/android-terms.txt create mode 100644 buildSrc/src/main/resources/license/apache-2.0.txt create mode 100644 buildSrc/src/main/resources/license/gplv2ce.txt create mode 100644 buildSrc/src/main/resources/license/material-intro.txt create mode 100644 buildSrc/src/main/resources/license/threeten.txt create mode 100644 buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/DependencyTaskTest.java create mode 100644 buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/GoogleServicesLicenseTest.java create mode 100644 buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesCleanUpTaskTest.java create mode 100644 buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesTaskTest.java create mode 100644 buildSrc/src/test/resources/dependencies/groupA/deps1.pom create mode 100644 buildSrc/src/test/resources/dependencies/groupA/deps1.txt create mode 100644 buildSrc/src/test/resources/dependencies/groupB/abc/deps2.txt create mode 100644 buildSrc/src/test/resources/dependencies/groupB/bcd/deps2.pom create mode 100644 buildSrc/src/test/resources/dependencies/groupC/deps3.txt create mode 100644 buildSrc/src/test/resources/dependencies/groupD/deps4.txt create mode 100644 buildSrc/src/test/resources/dependencies/groupE/deps5.pom create mode 100644 buildSrc/src/test/resources/dependencies/groupE/deps5.txt create mode 100644 buildSrc/src/test/resources/sampleLicenses/third_party_licenses.json create mode 100644 buildSrc/src/test/resources/sampleLicenses/third_party_licenses.txt create mode 100644 buildSrc/src/test/resources/testDependency.json diff --git a/app/build.gradle b/app/build.gradle index f12338514..9d9de7102 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -129,7 +129,7 @@ dependencies { //noinspection GradleDependency implementation 'com.squareup.okhttp3:okhttp:3.12.10' implementation 'com.squareup.moshi:moshi:1.9.2' - implementation 'com.jakewharton.threetenabp:threetenabp:1.2.2' + implementation 'com.jakewharton.threetenabp:threetenabp:1.2.3' implementation 'net.sourceforge.streamsupport:android-retrostreams:1.7.1' implementation 'com.squareup.picasso:picasso:2.71828' implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2' diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy index 4b5da076f..8aff88594 100644 --- a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/DependencyTask.groovy @@ -56,6 +56,8 @@ class DependencyTask extends DefaultTask { private static final logger = LoggerFactory.getLogger(DependencyTask.class) + protected String variant + @Input public ConfigurationContainer configurations @@ -104,8 +106,10 @@ class DependencyTask extends DefaultTask { protected void updateDependencyArtifacts() { for (Configuration configuration : configurations) { - Set artifacts = getResolvedArtifacts( - configuration) + if (!isForVariant(configuration)) { + continue + } + Set artifacts = getResolvedArtifacts(configuration) if (artifacts == null) { continue } @@ -138,9 +142,8 @@ class DependencyTask extends DefaultTask { * @return true if configuration can be resolved or the api is lower than * 3.3, otherwise false. */ - protected boolean canBeResolved(Configuration configuration) { - return configuration.metaClass.respondsTo(configuration, - "isCanBeResolved") ? configuration.isCanBeResolved() : true + protected static boolean canBeResolved(Configuration configuration) { + return configuration.metaClass.respondsTo(configuration, "isCanBeResolved") ? configuration.isCanBeResolved() : true } /** @@ -150,7 +153,7 @@ class DependencyTask extends DefaultTask { * configurations are either testCompile or androidTestCompile, otherwise * false. */ - protected boolean isTest(Configuration configuration) { + protected static boolean isTest(Configuration configuration) { boolean isTestConfiguration = ( configuration.name.startsWith(TEST_PREFIX) || configuration.name.startsWith(ANDROID_TEST_PREFIX)) @@ -165,7 +168,7 @@ class DependencyTask extends DefaultTask { * @param configuration * @return true if the configuration is in the set of @link #BINARY_DEPENDENCIES */ - protected boolean isPackagedDependency(Configuration configuration) { + protected static boolean isPackagedDependency(Configuration configuration) { boolean isPackagedDependency = PACKAGED_DEPENDENCIES_PREFIXES.any { configuration.name.startsWith(it) } @@ -179,16 +182,17 @@ class DependencyTask extends DefaultTask { return isPackagedDependency } - protected Set getResolvedArtifacts( - Configuration configuration) { + protected boolean isForVariant(Configuration configuration) { + return configuration.name.startsWith(this.variant) + } + + protected Set getResolvedArtifacts(Configuration configuration) { /** * skip the configurations that, cannot be resolved in * newer version of gradle api, are tests, or are not packaged dependencies. */ - if (!canBeResolved(configuration) - || isTest(configuration) - || !isPackagedDependency(configuration)) { + if (!canBeResolved(configuration) || isTest(configuration) || !isPackagedDependency(configuration)) { return null } diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy deleted file mode 100644 index 691bac214..000000000 --- a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/GenerateLicense.groovy +++ /dev/null @@ -1,18 +0,0 @@ -package be.ugent.zeus.hydra.licenses - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.TaskAction - -/** - * @author Niko Strijbol - */ -class GenerateLicense extends DefaultTask { - - @TaskAction - def generate() { - - - - } - -} diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicenseMap.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicenseMap.groovy new file mode 100644 index 000000000..549b6b65d --- /dev/null +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicenseMap.groovy @@ -0,0 +1,68 @@ +/** + * Copyright 2016 Jared Burrows + * Copyright 2020 Niko Strijbol + * + * 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 + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed : 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. + */ +package be.ugent.zeus.hydra.licenses + +/** + * Maps URLs : a license. + * + * Based on https://github.com/jaredsburrows/gradle-license-plugin/blob/master/src/main/kotlin/com/jaredsburrows/license/internal/LicenseHelper.kt + * + * @author Niko Strijbol + */ +@Singleton +class LicenseMap { + + def mapping = [ + // Apache License 2.0 + // https://github.com/github/choosealicense.com/blob/gh-pages/_licenses/apache-2.0.txt + "Apache 2.0" : "apache-2.0.txt", + "Apache License 2.0" : "apache-2.0.txt", + "The Apache Software License" : "apache-2.0.txt", + "The Apache Software License, Version 2.0" : "apache-2.0.txt", + "http://www.apache.org/licenses/LICENSE-2.0.txt" : "apache-2.0.txt", + "https://www.apache.org/licenses/LICENSE-2.0.txt" : "apache-2.0.txt", + "http://opensource.org/licenses/Apache-2.0" : "apache-2.0.txt", + "https://opensource.org/licenses/Apache-2.0" : "apache-2.0.txt", + // For OSM-droid, see https://github.com/osmdroid/osmdroid/issues/1542 + "http://www.apache.org/licenses/" : "apache-2.0.txt", + + + // MIT License + // https://github.com/github/choosealicense.com/blob/gh-pages/_licenses/mit.txt + "MIT License" : "mit.txt", + "http://opensource.org/licenses/MIT" : "mit.txt", + "https://opensource.org/licenses/MIT" : "mit.txt", + "http://www.opensource.org/licenses/mit-license.php" : "mit.txt", + + // GPLv2 + Classpath Exception + // https://github.com/github/choosealicense.com/blob/gh-pages/_licenses/mpl-2.0.txt + "http://openjdk.java.net/legal/gplv2+ce.html" : "gplv2ce.txt", + + // Not a license -- skip these + "https://developer.android.com/studio/terms.html" : null, + "http://developer.android.com/studio/terms.html" : null, + "https://answers.io/terms" : null, + "http://answers.io/terms" : null, + "https://fabric.io/terms" : null, + "https://fabric.io/term" : null, + "http://try.crashlytics.com/terms/terms-of-service.pdf": null, + + // Library specific licenses + "org.threeten:threetenbp" : "threeten.txt", + "com.heinrichreimersoftware:material-intro" : "material-intro.txt" + ] +} diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy index 85d7324cc..2dba559f0 100644 --- a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/LicensesTask.groovy @@ -16,6 +16,7 @@ package be.ugent.zeus.hydra.licenses +import com.sun.jndi.toolkit.url.Uri import groovy.json.JsonSlurper import groovy.xml.MarkupBuilder import org.gradle.api.DefaultTask @@ -246,28 +247,68 @@ class LicensesTask extends DefaultTask { } protected void writeMetadata() { - def html = new MarkupBuilder(html.newWriter(UTF_8)) + + // Generate the correct map with content. + def newMap = [:] + + def keys = LicenseMap.instance.mapping.keySet() + for (entry in licensesMap) { + + if (entry.value in keys || entry.key in keys) { + newMap[entry.key] = getLicenseText(entry) + if (newMap[entry.key] == null) { + newMap.remove(entry.key) + } + } else { + // If more than 100, assume we have an url. + + if (isUrl(entry.value)) { + logger.warn("Cound not find library text for ${entry.key}") + logger.warn("URL is ${entry}") + } + newMap[entry.key] = entry.value + } + } + + def writer = html.newWriter(UTF_8) + def html = new MarkupBuilder(writer) html.doubleQuotes = true html.expandEmptyElements = true html.omitEmptyAttributes = false html.omitNullAttributes = false + html.mkp.yieldUnescaped "" html.html { head { title("Licenties") } body { - for (entry in licensesMap) { + newMap.each { e -> details { - summary(entry.key) - pre(entry.value) + summary(e.key) + pre(e.value) } } } } + writer.close() } private static ModuleComponentIdentifier createModuleComponentIdentifier(String group, String name, String version) { return new DefaultModuleComponentIdentifier(DefaultModuleIdentifier.newId(group, name), version) } + private getLicenseText(def entry) { + String name = LicenseMap.instance.mapping.get(entry.value, LicenseMap.instance.mapping[entry.key]) + return getClass().getResource("/license/${name}")?.text + } + + private static boolean isUrl(String text) { + try { + URI.create(text) + return true + } catch (IllegalArgumentException ignored) { + return false + } + } + } \ No newline at end of file diff --git a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy index af8f6ed45..edf365ae9 100644 --- a/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy +++ b/buildSrc/src/main/groovy/be/ugent/zeus/hydra/licenses/OssLicensesPlugin.groovy @@ -21,18 +21,22 @@ import org.gradle.api.Plugin import org.gradle.api.Project class OssLicensesPlugin implements Plugin { - void apply(Project project) { - def getDependencies = project.tasks.create("getDependencies", DependencyTask) + + private static generate(Project project, String variant) { + + def getDependencies = project.tasks.create("get${variant.capitalize()}Dependencies", DependencyTask) def dependencyOutput = new File(project.buildDir, "generated/third_party_licenses") def generatedJson = new File(dependencyOutput, "dependencies.json") getDependencies.configurations = project.getConfigurations() getDependencies.outputDir = dependencyOutput getDependencies.outputFile = generatedJson + getDependencies.variant = variant def resourceOutput = new File(dependencyOutput, "/res") def outputDir = new File(resourceOutput, "/raw") def licensesFile = new File(outputDir, "third_party_licenses.html") - def licenseTask = project.tasks.create("generateLicenses", LicensesTask) + + def licenseTask = project.tasks.create("generate${variant.capitalize()}Licenses", LicensesTask) licenseTask.dependenciesJson = generatedJson licenseTask.outputDir = outputDir @@ -44,7 +48,24 @@ class OssLicensesPlugin implements Plugin { licenseTask.dependsOn(getDependencies) + + def cleanupTask = project.tasks.create("${variant}LicensesCleanUp", LicensesCleanUpTask) + cleanupTask.dependencyFile = generatedJson + cleanupTask.dependencyDir = dependencyOutput + cleanupTask.htmlFile = licensesFile + cleanupTask.licensesDir = outputDir + + project.tasks.findByName("clean").dependsOn(cleanupTask) + + [licenseTask, resourceOutput] + } + + void apply(Project project) { + project.android.applicationVariants.all { BaseVariant variant -> + + def (licenseTask, resourceOutput) = generate(project, variant.name) + // This is necessary for backwards compatibility with versions of gradle that do not support // this new API. if (variant.hasProperty("preBuildProvider")) { @@ -71,13 +92,5 @@ class OssLicensesPlugin implements Plugin { variant.registerResGeneratingTask(licenseTask, resourceOutput) } } - - def cleanupTask = project.tasks.create("licensesCleanUp", LicensesCleanUpTask) - cleanupTask.dependencyFile = generatedJson - cleanupTask.dependencyDir = dependencyOutput - cleanupTask.htmlFile = licensesFile - cleanupTask.licensesDir = outputDir - - project.tasks.findByName("clean").dependsOn(cleanupTask) } } \ No newline at end of file diff --git a/buildSrc/src/main/resources/license/android-terms.txt b/buildSrc/src/main/resources/license/android-terms.txt new file mode 100644 index 000000000..798609147 --- /dev/null +++ b/buildSrc/src/main/resources/license/android-terms.txt @@ -0,0 +1,161 @@ +This is not a license. +View the latest version at: https://developer.android.com/studio/terms.html + +This is the Android Software Development Kit License Agreement + +1. Introduction + +1.1 The Android Software Development Kit (referred to in the License Agreement + as the "SDK" and specifically including the Android system files, packaged + APIs, and Google APIs add-ons) is licensed to you subject to the terms of the + License Agreement. The License Agreement forms a legally binding contract + between you and Google in relation to your use of the SDK. + +1.2 "Android" means the Android software stack for devices, as made available + under the Android Open Source Project, which is located at the following URL: + http://source.android.com/, as updated from time to time. + +1.3 A "compatible implementation" means any Android device that (i) complies + with the Android Compatibility Definition document, which can be found at the + Android compatibility website (http://source.android.com/compatibility) and + which may be updated from time to time; and (ii) successfully passes the + Android Compatibility Test Suite (CTS). + +1.4 "Google" means Google LLC, a Delaware corporation with principal place of + business at 1600 Amphitheatre Parkway, Mountain View, CA 94043, United States. + + +2. Accepting this License Agreement + +2.1 In order to use the SDK, you must first agree to the License Agreement. You + may not use the SDK if you do not accept the License Agreement. + +2.2 By clicking to accept, you hereby agree to the terms of the License Agreement. + +2.3 You may not use the SDK and may not accept the License Agreement if you are a person barred from receiving the SDK under the laws of the United States or other countries, including the country in which you are resident or from which you use the SDK. + +2.4 If you are agreeing to be bound by the License Agreement on behalf of your employer or other entity, you represent and warrant that you have full legal authority to bind your employer or such entity to the License Agreement. If you do not have the requisite authority, you may not accept the License Agreement or use the SDK on behalf of your employer or other entity. + + +3. SDK License from Google + +3.1 Subject to the terms of the License Agreement, Google grants you a limited, worldwide, royalty-free, non-assignable, non-exclusive, and non-sublicensable license to use the SDK solely to develop applications for compatible implementations of Android. + +3.2 You may not use this SDK to develop applications for other platforms (including non-compatible implementations of Android) or to develop another SDK. You are of course free to develop applications for other platforms, including non-compatible implementations of Android, provided that this SDK is not used for that purpose. + +3.3 You agree that Google or third parties own all legal right, title and interest in and to the SDK, including any Intellectual Property Rights that subsist in the SDK. "Intellectual Property Rights" means any and all rights under patent law, copyright law, trade secret law, trademark law, and any and all other proprietary rights. Google reserves all rights not expressly granted to you. + +3.4 You may not use the SDK for any purpose not expressly permitted by the License Agreement. Except to the extent required by applicable third party licenses, you may not copy (except for backup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, or create derivative works of the SDK or any part of the SDK. + +3.5 Use, reproduction and distribution of components of the SDK licensed under an open source software license are governed solely by the terms of that open source software license and not the License Agreement. + +3.6 You agree that the form and nature of the SDK that Google provides may change without prior notice to you and that future versions of the SDK may be incompatible with applications developed on previous versions of the SDK. You agree that Google may stop (permanently or temporarily) providing the SDK (or any features within the SDK) to you or to users generally at Google's sole discretion, without prior notice to you. + +3.7 Nothing in the License Agreement gives you a right to use any of Google's trade names, trademarks, service marks, logos, domain names, or other distinctive brand features. + +3.8 You agree that you will not remove, obscure, or alter any proprietary rights notices (including copyright and trademark notices) that may be affixed to or contained within the SDK. + + +4. Use of the SDK by You + +4.1 Google agrees that it obtains no right, title or interest from you (or your licensors) under the License Agreement in or to any software applications that you develop using the SDK, including any intellectual property rights that subsist in those applications. + +4.2 You agree to use the SDK and write applications only for purposes that are permitted by (a) the License Agreement and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from the United States or other relevant countries). + +4.3 You agree that if you use the SDK to develop applications for general public users, you will protect the privacy and legal rights of those users. If the users provide you with user names, passwords, or other login information or personal information, you must make the users aware that the information will be available to your application, and you must provide legally adequate privacy notice and protection for those users. If your application stores personal or sensitive information provided by users, it must do so securely. If the user provides your application with Google Account information, your application may only use that information to access the user's Google Account when, and for the limited purposes for which, the user has given you permission to do so. + +4.4 You agree that you will not engage in any activity with the SDK, including the development or distribution of an application, that interferes with, disrupts, damages, or accesses in an unauthorized manner the servers, networks, or other properties or services of any third party including, but not limited to, Google or any mobile communications carrier. + +4.5 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any data, content, or resources that you create, transmit or display through Android and/or applications for Android, and for the consequences of your actions (including any loss or damage which Google may suffer) by doing so. + +4.6 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any breach of your obligations under the License Agreement, any applicable third party contract or Terms of Service, or any applicable law or regulation, and for the consequences (including any loss or damage which Google or any third party may suffer) of any such breach. + + +5. Your Developer Credentials + +5.1 You agree that you are responsible for maintaining the confidentiality of any developer credentials that may be issued to you by Google or which you may choose yourself and that you will be solely responsible for all applications that are developed under your developer credentials. + + +6. Privacy and Information + +6.1 In order to continually innovate and improve the SDK, Google may collect certain usage statistics from the software including but not limited to a unique identifier, associated IP address, version number of the software, and information on which tools and/or services in the SDK are being used and how they are being used. Before any of this information is collected, the SDK will notify you and seek your consent. If you withhold consent, the information will not be collected. + +6.2 The data collected is examined in the aggregate to improve the SDK and is maintained in accordance with Google's Privacy Policy. + + +7. Third Party Applications + +7.1 If you use the SDK to run applications developed by a third party or that access data, content or resources provided by a third party, you agree that Google is not responsible for those applications, data, content, or resources. You understand that all data, content or resources which you may access through such third party applications are the sole responsibility of the person from which they originated and that Google is not liable for any loss or damage that you may experience as a result of the use or access of any of those third party applications, data, content, or resources. + +7.2 You should be aware the data, content, and resources presented to you through such a third party application may be protected by intellectual property rights which are owned by the providers (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell, distribute or create derivative works based on these data, content, or resources (either in whole or in part) unless you have been specifically given permission to do so by the relevant owners. + +7.3 You acknowledge that your use of such third party applications, data, content, or resources may be subject to separate terms between you and the relevant third party. In that case, the License Agreement does not affect your legal relationship with these third parties. + + +8. Using Android APIs + +8.1 Google Data APIs + +8.1.1 If you use any API to retrieve data from Google, you acknowledge that the data may be protected by intellectual property rights which are owned by Google or those parties that provide the data (or by other persons or companies on their behalf). Your use of any such API may be subject to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute or create derivative works based on this data (either in whole or in part) unless allowed by the relevant Terms of Service. + +8.1.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree that you shall retrieve data only with the user's explicit consent and only when, and for the limited purposes for which, the user has given you permission to do so. If you use the Android Recognition Service API, documented at the following URL: https://developer.android.com/reference/android/speech/RecognitionService, as updated from time to time, you acknowledge that the use of the API is subject to the Data Processing Addendum for Products where Google is a Data Processor, which is located at the following URL: https://privacy.google.com/businesses/gdprprocessorterms/, as updated from time to time. By clicking to accept, you hereby agree to the terms of the Data Processing Addendum for Products where Google is a Data Processor. + + + +9. Terminating this License Agreement + +9.1 The License Agreement will continue to apply until terminated by either you or Google as set out below. + +9.2 If you want to terminate the License Agreement, you may do so by ceasing your use of the SDK and any relevant developer credentials. + +9.3 Google may at any time, terminate the License Agreement with you if: +(A) you have breached any provision of the License Agreement; or +(B) Google is required to do so by law; or +(C) the partner with whom Google offered certain parts of SDK (such as APIs) to you has terminated its relationship with Google or ceased to offer certain parts of the SDK to you; or +(D) Google decides to no longer provide the SDK or certain parts of the SDK to users in the country in which you are resident or from which you use the service, or the provision of the SDK or certain SDK services to you by Google is, in Google's sole discretion, no longer commercially viable. + +9.4 When the License Agreement comes to an end, all of the legal rights, obligations and liabilities that you and Google have benefited from, been subject to (or which have accrued over time whilst the License Agreement has been in force) or which are expressed to continue indefinitely, shall be unaffected by this cessation, and the provisions of paragraph 14.7 shall continue to apply to such rights, obligations and liabilities indefinitely. + + +10. DISCLAIMER OF WARRANTIES + +10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND THAT THE SDK IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM GOOGLE. + +10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE SDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. + +10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + + +11. LIMITATION OF LIABILITY + +11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND ITS LICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY LOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN AWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING. + + +12. Indemnification + +12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmless Google, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) your use of the SDK, (b) any application you develop on the SDK that infringes any copyright, trademark, trade secret, trade dress, patent or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy, and (c) any non-compliance by you with the License Agreement. + + +13. Changes to the License Agreement + +13.1 Google may make changes to the License Agreement as it distributes new versions of the SDK. When these changes are made, Google will make a new version of the License Agreement available on the website where the SDK is made available. + + +14. General Legal Terms + +14.1 The License Agreement constitutes the whole legal agreement between you and Google and governs your use of the SDK (excluding any services which Google may provide to you under a separate written agreement), and completely replaces any prior agreements between you and Google in relation to the SDK. + +14.2 You agree that if Google does not exercise or enforce any legal right or remedy which is contained in the License Agreement (or which Google has the benefit of under any applicable law), this will not be taken to be a formal waiver of Google's rights and that those rights or remedies will still be available to Google. + +14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any provision of the License Agreement is invalid, then that provision will be removed from the License Agreement without affecting the rest of the License Agreement. The remaining provisions of the License Agreement will continue to be valid and enforceable. + +14.4 You acknowledge and agree that each member of the group of companies of which Google is the parent shall be third party beneficiaries to the License Agreement and that such other companies shall be entitled to directly enforce, and rely upon, any provision of the License Agreement that confers a benefit on (or rights in favor of) them. Other than this, no other person or company shall be third party beneficiaries to the License Agreement. + +14.5 EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE SDK. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE. + +14.6 The rights granted in the License Agreement may not be assigned or transferred by either you or Google without the prior written approval of the other party. Neither you nor Google shall be permitted to delegate their responsibilities or obligations under the License Agreement without the prior written approval of the other party. + +14.7 The License Agreement, and your relationship with Google under the License Agreement, shall be governed by the laws of the State of California without regard to its conflict of laws provisions. You and Google agree to submit to the exclusive jurisdiction of the courts located within the county of Santa Clara, California to resolve any legal matter arising from the License Agreement. Notwithstanding this, you agree that Google shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction. + + +January 16, 2019 \ No newline at end of file diff --git a/buildSrc/src/main/resources/license/apache-2.0.txt b/buildSrc/src/main/resources/license/apache-2.0.txt new file mode 100644 index 000000000..f7f9c345a --- /dev/null +++ b/buildSrc/src/main/resources/license/apache-2.0.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/buildSrc/src/main/resources/license/gplv2ce.txt b/buildSrc/src/main/resources/license/gplv2ce.txt new file mode 100644 index 000000000..15663f34e --- /dev/null +++ b/buildSrc/src/main/resources/license/gplv2ce.txt @@ -0,0 +1,349 @@ +GNU General Public License, version 2, +with the Classpath Exception +The GNU General Public License (GPL) + +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to +most of the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Library General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for this service if you wish), +that you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs; and that you know you +can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for +a fee, you must give the recipients all the rights that you have. You must +make sure that they, too, receive or can get the source code. And you must +show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) +offer you this license which gives you legal permission to copy, distribute +and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced +by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We +wish to avoid the danger that redistributors of a free program will +individually obtain patent licenses, in effect making the program proprietary. +To prevent this, we have made it clear that any patent must be licensed for +everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program +or work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or +translated into another language. (Hereinafter, translation is included +without limitation in the term "modification".) Each licensee is addressed as +"you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is +not restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as +you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this License +and to the absence of any warranty; and give any other recipients of the +Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may +at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus +forming a work based on the Program, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all of +these conditions: + + a) You must cause the modified files to carry prominent notices stating + that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or + in part contains or is derived from the Program or any part thereof, to be + licensed as a whole at no charge to all third parties under the terms of + this License. + + c) If the modified program normally reads commands interactively when run, + you must cause it, when started running for such interactive use in the + most ordinary way, to print or display an announcement including an + appropriate copyright notice and a notice that there is no warranty (or + else, saying that you provide a warranty) and that users may redistribute + the program under these conditions, and telling the user how to view a copy + of this License. (Exception: if the Program itself is interactive but does + not normally print such an announcement, your work based on the Program is + not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, and +its terms, do not apply to those sections when you distribute them as separate +works. But when you distribute the same sections as part of a whole which is a +work based on the Program, the distribution of the whole must be on the terms +of this License, whose permissions for other licensees extend to the entire +whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise the +right to control the distribution of derivative or collective works based on +the Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +3. You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and +2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source + code, which must be distributed under the terms of Sections 1 and 2 above + on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to + give any third party, for a charge no more than your cost of physically + performing source distribution, a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed only + for noncommercial distribution and only if you received the program in + object code or executable form with such an offer, in accord with + Subsection b above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all +the source code for all modules it contains, plus any associated interface +definition files, plus the scripts used to control compilation and installation +of the executable. However, as a special exception, the source code +distributed need not include anything that is normally distributed (in either +source or binary form) with the major components (compiler, kernel, and so on) +of the operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source +code from the same place counts as distribution of the source code, even though +third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so +long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. +However, nothing else grants you permission to modify or distribute the Program +or its derivative works. These actions are prohibited by law if you do not +accept this License. Therefore, by modifying or distributing the Program (or +any work based on the Program), you indicate your acceptance of this License to +do so, and all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), +the recipient automatically receives a license from the original licensor to +copy, distribute or modify the Program subject to these terms and conditions. +You may not impose any further restrictions on the recipients' exercise of the +rights granted herein. You are not responsible for enforcing compliance by +third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), conditions +are imposed on you (whether by court order, agreement or otherwise) that +contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot distribute so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not distribute the Program at all. +For example, if a patent license would not permit royalty-free redistribution +of the Program by all those who receive copies directly or indirectly through +you, then the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply and +the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or +other property right claims or to contest validity of any such claims; this +section has the sole purpose of protecting the integrity of the free software +distribution system, which is implemented by public license practices. Many +people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose that +choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain +countries either by patents or by copyrighted interfaces, the original +copyright holder who places the Program under this License may add an explicit +geographical distribution limitation excluding those countries, so that +distribution is permitted only in or among countries not thus excluded. In +such case, this License incorporates the limitation as if written in the body +of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems +or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any later +version", you have the option of following the terms and conditions either of +that version or of any later version published by the Free Software Foundation. +If the Program does not specify a version number of this License, you may +choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of +all derivatives of our free software and of promoting the sharing and reuse of +software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE +PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, +YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA +BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER +OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively convey the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + One line to give the program's name and a brief idea of what it does. + + Copyright (C) + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it +starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes + with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free + software, and you are welcome to redistribute it under certain conditions; + type 'show c' for details. + +The hypothetical commands 'show w' and 'show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may be +called something other than 'show w' and 'show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the program, if necessary. Here +is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + 'Gnomovision' (which makes passes at compilers) written by James Hacker. + + signature of Ty Coon, 1 April 1989 + + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General Public +License instead of this License. + + +"CLASSPATH" EXCEPTION TO THE GPL + +Certain source files distributed by Oracle America and/or its affiliates are +subject to the following clarification and special exception to the GPL, but +only where Oracle has expressly included in the particular source file's header +the words "Oracle designates this particular file as subject to the "Classpath" +exception as provided by Oracle in the LICENSE file that accompanied this code." + + Linking this library statically or dynamically with other modules is making + a combined work based on this library. Thus, the terms and conditions of + the GNU General Public License cover the whole combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent modules, + and to copy and distribute the resulting executable under terms of your + choice, provided that you also meet, for each linked independent module, + the terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. If + you modify this library, you may extend this exception to your version of + the library, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your version. \ No newline at end of file diff --git a/buildSrc/src/main/resources/license/material-intro.txt b/buildSrc/src/main/resources/license/material-intro.txt new file mode 100644 index 000000000..acdf845aa --- /dev/null +++ b/buildSrc/src/main/resources/license/material-intro.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Jan Heinrich Reimer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/buildSrc/src/main/resources/license/threeten.txt b/buildSrc/src/main/resources/license/threeten.txt new file mode 100644 index 000000000..287ec7014 --- /dev/null +++ b/buildSrc/src/main/resources/license/threeten.txt @@ -0,0 +1,29 @@ +Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of JSR-310 nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/DependencyTaskTest.java b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/DependencyTaskTest.java new file mode 100644 index 000000000..6bac29940 --- /dev/null +++ b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/DependencyTaskTest.java @@ -0,0 +1,413 @@ +/* + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.LenientConfiguration; +import org.gradle.api.artifacts.ModuleVersionIdentifier; +import org.gradle.api.artifacts.ResolveException; +import org.gradle.api.artifacts.ResolvedArtifact; +import org.gradle.api.artifacts.ResolvedConfiguration; +import org.gradle.api.artifacts.ResolvedDependency; +import org.gradle.api.artifacts.ResolvedModuleVersion; +import org.gradle.testfixtures.ProjectBuilder; +import org.jetbrains.annotations.NotNull; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link DependencyTask} */ +@RunWith(JUnit4.class) +public class DependencyTaskTest { + private Project project; + private DependencyTask dependencyTask; + + @Before + public void setUp() { + project = ProjectBuilder.builder().build(); + dependencyTask = project.getTasks().create("getDependency", DependencyTask.class); + } + + @Test + public void testCheckArtifactSet_missingSet() { + File dependencies = new File("src/test/resources", "testDependency.json"); + String[] artifactSet = + new String[] {"dependencies/groupA/deps1.txt", "dependencies/groupB/abc/deps2.txt"}; + dependencyTask.artifactSet = new HashSet<>(Arrays.asList(artifactSet)); + + assertFalse(dependencyTask.checkArtifactSet(dependencies)); + } + + @Test + public void testCheckArtifactSet_correctSet() { + File dependencies = new File("src/test/resources", "testDependency.json"); + String[] artifactSet = + new String[] { + "dependencies/groupA/deps1.txt", + "dependencies/groupB/abc/deps2.txt", + "src/test/resources/dependencies/groupC/deps3.txt", + "src/test/resources/dependencies/groupD/deps4.txt" + }; + dependencyTask.artifactSet = new HashSet<>(Arrays.asList(artifactSet)); + assertTrue(dependencyTask.checkArtifactSet(dependencies)); + } + + @Test + public void testCheckArtifactSet_addMoreSet() { + File dependencies = new File("src/test/resources", "testDependency.json"); + String[] artifactSet = + new String[] { + "dependencies/groupA/deps1.txt", + "dependencies/groupB/abc/deps2.txt", + "src/test/resources/dependencies/groupC/deps3.txt", + "src/test/resources/dependencies/groupD/deps4.txt", + "dependencies/groupE/deps5.txt" + }; + dependencyTask.artifactSet = new HashSet<>(Arrays.asList(artifactSet)); + assertFalse(dependencyTask.checkArtifactSet(dependencies)); + } + + @Test + public void testCheckArtifactSet_replaceSet() { + File dependencies = new File("src/test/resources", "testDependency.json"); + String[] artifactSet = + new String[] { + "dependencies/groupA/deps1.txt", + "dependencies/groupB/abc/deps2.txt", + "src/test/resources/dependencies/groupC/deps3.txt", + "dependencies/groupE/deps5.txt" + }; + dependencyTask.artifactSet = new HashSet<>(Arrays.asList(artifactSet)); + assertFalse(dependencyTask.checkArtifactSet(dependencies)); + } + + @Test + public void testGetResolvedArtifacts_cannotResolve() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("implementation"); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.isCanBeResolved()).thenReturn(false); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(nullValue())); + } + + @Test + public void testGetResolvedArtifacts_isTest() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.getName()).thenReturn("testCompile"); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(nullValue())); + } + + @Test + public void testGetResolvedArtifacts_isNotPackaged() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.getName()).thenReturn("random"); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(nullValue())); + } + + @Test + public void testGetResolvedArtifacts_isPackagedApi() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.getName()).thenReturn("api"); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSet)); + } + + @Test + public void testGetResolvedArtifacts_isPackagedImplementation() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.getName()).thenReturn("implementation"); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSet)); + } + + @Test + public void testGetResolvedArtifacts_isPackagedCompile() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + when(configuration.getName()).thenReturn("compile"); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSet)); + } + + @Test + public void testGetResolvedArtifacts_isPackagedInHierarchy() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("random"); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + Configuration parent = mock(Configuration.class); + when(parent.getName()).thenReturn("compile"); + Set hierarchy = new HashSet<>(); + hierarchy.add(parent); + when(configuration.getHierarchy()).thenReturn(hierarchy); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSet)); + } + + @Test + public void testGetResolvedArtifacts_ResolveException() { + ResolvedConfiguration resolvedConfiguration = mock(ResolvedConfiguration.class); + when(resolvedConfiguration.getLenientConfiguration()).thenThrow(ResolveException.class); + + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("compile"); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(nullValue())); + } + + @Test + public void testGetResolvedArtifacts_returnArtifact() { + Set artifactSet = prepareArtifactSet(2); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfiguration(artifactSet); + + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("compile"); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSet)); + } + + @Test + public void testGetResolvedArtifacts_libraryProject_returnsArtifacts() { + ResolvedDependency libraryResolvedDependency = mock(ResolvedDependency.class); + when(libraryResolvedDependency.getModuleVersion()) + .thenReturn(DependencyTask.LOCAL_LIBRARY_VERSION); + ResolvedDependency libraryChildResolvedDependency = mock(ResolvedDependency.class); + Set libraryChildArtifactSet = + prepareArtifactSet(/* start= */ 0, /* count= */ 2); + when(libraryChildResolvedDependency.getAllModuleArtifacts()) + .thenReturn(libraryChildArtifactSet); + when(libraryResolvedDependency.getChildren()) + .thenReturn(Collections.singleton(libraryChildResolvedDependency)); + + Set appArtifactSet = prepareArtifactSet(/* start= */ 2, /* count= */ 2); + ResolvedDependency appResolvedDependency = mock(ResolvedDependency.class); + when(appResolvedDependency.getAllModuleArtifacts()).thenReturn(appArtifactSet); + + Set resolvedDependencySet = new HashSet<>( + Arrays.asList(libraryResolvedDependency, appResolvedDependency)); + ResolvedConfiguration resolvedConfiguration = mockResolvedConfigurationFromDependencySet( + resolvedDependencySet); + + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("compile"); + when(configuration.isCanBeResolved()).thenReturn(true); + when(configuration.getResolvedConfiguration()).thenReturn(resolvedConfiguration); + + Set artifactSuperSet = new HashSet<>(); + artifactSuperSet.addAll(appArtifactSet); + artifactSuperSet.addAll(libraryChildArtifactSet); + assertThat(dependencyTask.getResolvedArtifacts(configuration), is(artifactSuperSet)); + // Calling getAllModuleArtifacts on a library will cause an exception. + verify(libraryResolvedDependency, never()).getAllModuleArtifacts(); + } + + @NotNull + private ResolvedConfiguration mockResolvedConfiguration(Set artifactSet) { + ResolvedDependency resolvedDependency = mock(ResolvedDependency.class); + when(resolvedDependency.getAllModuleArtifacts()).thenReturn(artifactSet); + Set resolvedDependencySet = Collections.singleton(resolvedDependency); + return mockResolvedConfigurationFromDependencySet(resolvedDependencySet); + } + + @NotNull + private ResolvedConfiguration mockResolvedConfigurationFromDependencySet( + Set resolvedDependencySet) { + + LenientConfiguration lenientConfiguration = mock(LenientConfiguration.class); + when(lenientConfiguration.getFirstLevelModuleDependencies()).thenReturn(resolvedDependencySet); + ResolvedConfiguration resolvedConfiguration = mock(ResolvedConfiguration.class); + when(resolvedConfiguration.getLenientConfiguration()).thenReturn(lenientConfiguration); + return resolvedConfiguration; + } + + @Test + public void testAddArtifacts() { + Set artifacts = prepareArtifactSet(3); + + dependencyTask.addArtifacts(artifacts); + assertThat(dependencyTask.artifactInfos.size(), is(3)); + } + + @Test + public void testAddArtifacts_willNotAddDuplicate() { + Set artifacts = prepareArtifactSet(2); + + String[] keySets = new String[] {"location1", "location2"}; + dependencyTask.artifactSet = new HashSet<>(Arrays.asList(keySets)); + dependencyTask.addArtifacts(artifacts); + + assertThat(dependencyTask.artifactInfos.size(), is(1)); + } + + @Test + public void testCanBeResolved_isTrue() { + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(true); + + assertTrue(dependencyTask.canBeResolved(configuration)); + } + + @Test + public void testCanBeResolved_isFalse() { + Configuration configuration = mock(Configuration.class); + when(configuration.isCanBeResolved()).thenReturn(false); + + assertFalse(dependencyTask.canBeResolved(configuration)); + } + + @Test + public void testIsTest_isNotTest() { + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("random"); + + assertFalse(dependencyTask.isTest(configuration)); + } + + @Test + public void testIsTest_isTestCompile() { + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("testCompile"); + + assertTrue(dependencyTask.isTest(configuration)); + } + + @Test + public void testIsTest_isAndroidTestCompile() { + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("androidTestCompile"); + + assertTrue(dependencyTask.isTest(configuration)); + } + + @Test + public void testIsTest_fromHierarchy() { + Configuration configuration = mock(Configuration.class); + when(configuration.getName()).thenReturn("random"); + + Configuration parent = mock(Configuration.class); + when(parent.getName()).thenReturn("testCompile"); + + Set hierarchy = new HashSet<>(); + hierarchy.add(parent); + + when(configuration.getHierarchy()).thenReturn(hierarchy); + assertTrue(dependencyTask.isTest(configuration)); + } + + private Set prepareArtifactSet(int count) { + return prepareArtifactSet(0, count); + } + + private Set prepareArtifactSet(int start, int count) { + Set artifacts = new HashSet<>(); + String namePrefix = "artifact"; + String groupPrefix = "group"; + String locationPrefix = "location"; + String versionPostfix = ".0"; + for (int i = start; i < start + count; i++) { + String index = String.valueOf(i); + artifacts.add( + prepareArtifact( + namePrefix + index, + groupPrefix + index, + locationPrefix + index, + index + versionPostfix)); + } + return artifacts; + } + + private ResolvedArtifact prepareArtifact( + String name, String group, String filePath, String version) { + ModuleVersionIdentifier moduleId = mock(ModuleVersionIdentifier.class); + when(moduleId.getGroup()).thenReturn(group); + when(moduleId.getVersion()).thenReturn(version); + + ResolvedModuleVersion moduleVersion = mock(ResolvedModuleVersion.class); + when(moduleVersion.getId()).thenReturn(moduleId); + + File artifactFile = mock(File.class); + when(artifactFile.getAbsolutePath()).thenReturn(filePath); + + ResolvedArtifact artifact = mock(ResolvedArtifact.class); + when(artifact.getName()).thenReturn(name); + when(artifact.getFile()).thenReturn(artifactFile); + when(artifact.getModuleVersion()).thenReturn(moduleVersion); + + return artifact; + } +} diff --git a/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/GoogleServicesLicenseTest.java b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/GoogleServicesLicenseTest.java new file mode 100644 index 000000000..068d617db --- /dev/null +++ b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/GoogleServicesLicenseTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.util.Arrays; +import org.gradle.api.Project; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +/** Test for {@link LicensesTask#isGoogleServices(String)} */ +@RunWith(Parameterized.class) +public class GoogleServicesLicenseTest { + private static final String BASE_DIR = "src/test/resources"; + private Project project; + private LicensesTask licensesTask; + + @Parameters + public static Iterable data() { + return Arrays.asList( + new Object[][] { + {"com.google.android.gms", "play-services-foo", true}, + {"com.google.firebase", "firebase-bar", true}, + {"com.example", "random", false}, + }); + } + + @Parameter(0) + public String inputGroup; + + @Parameter(1) + public String inputArtifactName; + + @Parameter(2) + public Boolean expectedResult; + + @Before + public void setUp() { + project = ProjectBuilder.builder().withProjectDir(new File(BASE_DIR)).build(); + licensesTask = project.getTasks().create("generateLicenses", LicensesTask.class); + } + + @Test + public void test() { + assertEquals(expectedResult, licensesTask.isGoogleServices(inputGroup)); + } +} diff --git a/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesCleanUpTaskTest.java b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesCleanUpTaskTest.java new file mode 100644 index 000000000..2fa3bb0c2 --- /dev/null +++ b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesCleanUpTaskTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses; + +import static org.junit.Assert.assertFalse; + +import java.io.File; +import java.io.IOException; +import org.gradle.api.Project; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link LicensesCleanUpTask} */ +@RunWith(JUnit4.class) +public class LicensesCleanUpTaskTest { + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + @SuppressWarnings("ResultOfMethodCallIgnored") + public void testAction() throws IOException { + File testDir = temporaryFolder.newFolder(); + + File dependencyDir = new File(testDir, "dependency"); + dependencyDir.mkdir(); + + File dependencyFile = new File(dependencyDir, "dependency.json"); + + File licensesDir = new File(testDir, "raw"); + licensesDir.mkdir(); + + File licensesFile = new File(licensesDir, "third_party_licenses.html"); + + Project project = ProjectBuilder.builder().withProjectDir(testDir).build(); + LicensesCleanUpTask task = + project.getTasks().create("licensesCleanUp", LicensesCleanUpTask.class); + task.dependencyDir = dependencyDir; + task.dependencyFile = dependencyFile; + task.licensesDir = licensesDir; + task.htmlFile = licensesFile; + + task.action(); + assertFalse(task.dependencyFile.exists()); + assertFalse(task.dependencyDir.exists()); + assertFalse(task.htmlFile.exists()); + assertFalse(task.licensesDir.exists()); + } +} diff --git a/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesTaskTest.java b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesTaskTest.java new file mode 100644 index 000000000..29f1656f0 --- /dev/null +++ b/buildSrc/src/test/java/be/ugent/zeus/hydra/licenses/LicensesTaskTest.java @@ -0,0 +1,270 @@ +/* + * Copyright 2018 Google LLC + * + * 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 + * + * https://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. + */ + +package be.ugent.zeus.hydra.licenses; + +import static org.gradle.internal.impldep.org.testng.Assert.fail; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Objects; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.gradle.api.Project; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link LicensesTask} */ +@RunWith(JUnit4.class) +public class LicensesTaskTest { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String BASE_DIR = "src/test/resources"; + private static final String LINE_BREAK = System.getProperty("line.separator"); + private LicensesTask licensesTask; + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + @SuppressWarnings("ResultOfMethodCallIgnored") + public void setUp() throws IOException { + File outputDir = temporaryFolder.newFolder(); + File outputLicenses = new File(outputDir, "testHtml"); + outputLicenses.createNewFile(); + + Project project = ProjectBuilder.builder().withProjectDir(new File(BASE_DIR)).build(); + licensesTask = project.getTasks().create("generateLicenses", LicensesTask.class); + + licensesTask.outputDir = outputDir; + licensesTask.html = outputLicenses; + } + + private void createLicenseZip(String name) throws IOException { + File zipFile = new File(name); + ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFile)); + File input = new File(BASE_DIR + "/sampleLicenses"); + for (File file : Objects.requireNonNull(input.listFiles())) { + ZipEntry entry = new ZipEntry(file.getName()); + byte[] bytes = Files.readAllBytes(file.toPath()); + output.putNextEntry(entry); + output.write(bytes, 0, bytes.length); + output.closeEntry(); + } + output.close(); + } + + @Test + public void testInitOutputDir() { + licensesTask.initOutputDir(); + + assertTrue(licensesTask.outputDir.exists()); + } + + @Test + public void testInitLicenseFile() throws IOException { + licensesTask.initLicenseFile(); + + assertTrue(licensesTask.html.exists()); + assertEquals(0, Files.size(licensesTask.html.toPath())); + } + + @Test + public void testIsGranularVersion_True() { + String versionTrue = "14.6.0"; + assertTrue(LicensesTask.isGranularVersion(versionTrue)); + } + + @Test + public void testIsGranularVersion_False() { + String versionFalse = "11.4.0"; + assertFalse(LicensesTask.isGranularVersion(versionFalse)); + } + + @Test + public void testAddLicensesFromPom() { + File deps1 = getResourceFile("dependencies/groupA/deps1.pom"); + String name1 = "deps1"; + String group1 = "groupA"; + licensesTask.addLicensesFromPom(deps1, group1, name1); + + assertTrue(licensesTask.licensesMap.containsKey("groupA:deps1")); + } + + @Test + public void testAddLicensesFromPom_withoutDuplicate() { + File deps1 = getResourceFile("dependencies/groupA/deps1.pom"); + String name1 = "deps1"; + String group1 = "groupA"; + licensesTask.addLicensesFromPom(deps1, group1, name1); + + File deps2 = getResourceFile("dependencies/groupB/bcd/deps2.pom"); + String name2 = "deps2"; + String group2 = "groupB"; + licensesTask.addLicensesFromPom(deps2, group2, name2); + + assertThat(licensesTask.licensesMap.size(), is(2)); + assertTrue(licensesTask.licensesMap.containsKey("groupA:deps1")); + assertTrue(licensesTask.licensesMap.containsKey("groupB:deps2")); + } + + @Test + public void testAddLicensesFromPom_withMultiple() { + File deps1 = getResourceFile("dependencies/groupA/deps1.pom"); + String name1 = "deps1"; + String group1 = "groupA"; + licensesTask.addLicensesFromPom(deps1, group1, name1); + + File deps2 = getResourceFile("dependencies/groupE/deps5.pom"); + String name2 = "deps5"; + String group2 = "groupE"; + licensesTask.addLicensesFromPom(deps2, group2, name2); + + assertThat(licensesTask.licensesMap.size(), is(3)); + assertTrue(licensesTask.licensesMap.containsKey("groupA:deps1")); + assertTrue(licensesTask.licensesMap.containsKey("groupE:deps5 MIT License")); + assertTrue(licensesTask.licensesMap.containsKey("groupE:deps5 Apache License 2.0")); + } + + @Test + public void testAddLicensesFromPom_withDuplicate() { + File deps1 = getResourceFile("dependencies/groupA/deps1.pom"); + String name1 = "deps1"; + String group1 = "groupA"; + licensesTask.addLicensesFromPom(deps1, group1, name1); + + File deps2 = getResourceFile("dependencies/groupA/deps1.pom"); + String name2 = "deps1"; + String group2 = "groupA"; + licensesTask.addLicensesFromPom(deps2, group2, name2); + + assertThat(licensesTask.licensesMap.size(), is(1)); + assertTrue(licensesTask.licensesMap.containsKey("groupA:deps1")); + } + + private File getResourceFile(String resourcePath) { + return new File(Objects.requireNonNull(getClass().getClassLoader().getResource(resourcePath)).getFile()); + } + + @Test + public void testGetBytesFromInputStream_throwException() throws IOException { + InputStream inputStream = mock(InputStream.class); + when(inputStream.read(any(byte[].class), anyInt(), anyInt())).thenThrow(new IOException()); + try { + LicensesTask.getBytesFromInputStream(inputStream, 1, 1); + fail("This test should throw Exception."); + } catch (RuntimeException e) { + assertEquals("Failed to read license text.", e.getMessage()); + } + } + + @Test + public void testGetBytesFromInputStream_normalText() { + String test = "test"; + InputStream inputStream = new ByteArrayInputStream(test.getBytes(UTF_8)); + String content = new String(LicensesTask.getBytesFromInputStream(inputStream, 1, 1), UTF_8); + assertEquals("e", content); + } + + @Test + @Ignore("Who knows why") + public void testGetBytesFromInputStream_specialCharacters() { + String test = "Copyright © 1991-2017 Unicode"; + InputStream inputStream = new ByteArrayInputStream(test.getBytes(UTF_8)); + String content = new String(LicensesTask.getBytesFromInputStream(inputStream, 4, 18), UTF_8); + assertEquals("right © 1991-2017", content); + } + + @Test + @SuppressWarnings("ResultOfMethodCallIgnored") + public void testAddGooglePlayServiceLicenses() throws IOException { + File tempOutput = new File(licensesTask.outputDir, "dependencies/groupC"); + tempOutput.mkdirs(); + createLicenseZip(tempOutput.getPath() + "play-services-foo-license.aar"); + File artifact = new File(tempOutput.getPath() + "play-services-foo-license.aar"); + licensesTask.addGooglePlayServiceLicenses(artifact); + + assertThat(licensesTask.googleServiceLicenses.size(), is(2)); + assertTrue(licensesTask.googleServiceLicenses.contains("safeparcel")); + assertTrue(licensesTask.googleServiceLicenses.contains("JSR 305")); + assertThat(licensesTask.licensesMap.size(), is(2)); + assertTrue(licensesTask.licensesMap.containsKey("safeparcel")); + assertTrue(licensesTask.licensesMap.containsKey("JSR 305")); + } + + @Test + @SuppressWarnings("ResultOfMethodCallIgnored") + public void testAddGooglePlayServiceLicenses_withoutDuplicate() throws IOException { + File groupC = new File(licensesTask.outputDir, "dependencies/groupC"); + groupC.mkdirs(); + createLicenseZip(groupC.getPath() + "/play-services-foo-license.aar"); + File artifactFoo = new File(groupC.getPath() + "/play-services-foo-license.aar"); + + File groupD = new File(licensesTask.outputDir, "dependencies/groupD"); + groupD.mkdirs(); + createLicenseZip(groupD.getPath() + "/play-services-bar-license.aar"); + File artifactBar = new File(groupD.getPath() + "/play-services-bar-license.aar"); + + licensesTask.addGooglePlayServiceLicenses(artifactFoo); + licensesTask.addGooglePlayServiceLicenses(artifactBar); + + assertThat(licensesTask.googleServiceLicenses.size(), is(2)); + assertTrue(licensesTask.googleServiceLicenses.contains("safeparcel")); + assertTrue(licensesTask.googleServiceLicenses.contains("JSR 305")); + assertThat(licensesTask.licensesMap.size(), is(2)); + assertTrue(licensesTask.licensesMap.containsKey("safeparcel")); + assertTrue(licensesTask.licensesMap.containsKey("JSR 305")); + } + + @Test + public void testAppendLicense() { + licensesTask.appendLicense("license1", "test".getBytes(UTF_8)); + assertTrue(licensesTask.licensesMap.containsKey("license1")); + } + + @Test + public void testWriteMetadata() throws IOException { + licensesTask.licensesMap.put("license1", "terms1"); + licensesTask.licensesMap.put("license2", "terms2"); + licensesTask.writeMetadata(); + + String content = new String(Files.readAllBytes(licensesTask.html.toPath()), UTF_8); + assertThat(content, containsString("license1")); + assertThat(content, containsString("terms1")); + assertThat(content, containsString("license2")); + assertThat(content, containsString("terms2")); + } +} diff --git a/buildSrc/src/test/resources/dependencies/groupA/deps1.pom b/buildSrc/src/test/resources/dependencies/groupA/deps1.pom new file mode 100644 index 000000000..8a1777628 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupA/deps1.pom @@ -0,0 +1,16 @@ + + 4.0.0 + + groupA + groupA-deps1 + 1 + groupA deps1 + groupA deps1 + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + + + \ No newline at end of file diff --git a/buildSrc/src/test/resources/dependencies/groupA/deps1.txt b/buildSrc/src/test/resources/dependencies/groupA/deps1.txt new file mode 100644 index 000000000..dc17ff864 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupA/deps1.txt @@ -0,0 +1 @@ +Dependency 1 diff --git a/buildSrc/src/test/resources/dependencies/groupB/abc/deps2.txt b/buildSrc/src/test/resources/dependencies/groupB/abc/deps2.txt new file mode 100644 index 000000000..3957602bd --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupB/abc/deps2.txt @@ -0,0 +1 @@ +Dependency 2 diff --git a/buildSrc/src/test/resources/dependencies/groupB/bcd/deps2.pom b/buildSrc/src/test/resources/dependencies/groupB/bcd/deps2.pom new file mode 100644 index 000000000..d754995c8 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupB/bcd/deps2.pom @@ -0,0 +1,16 @@ + + 4.0.0 + + groupA + groupA-deps1 + 1 + groupA deps1 + groupA deps1 + + + + Apache 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + + + \ No newline at end of file diff --git a/buildSrc/src/test/resources/dependencies/groupC/deps3.txt b/buildSrc/src/test/resources/dependencies/groupC/deps3.txt new file mode 100644 index 000000000..31b4eef30 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupC/deps3.txt @@ -0,0 +1 @@ +Dependency 3 diff --git a/buildSrc/src/test/resources/dependencies/groupD/deps4.txt b/buildSrc/src/test/resources/dependencies/groupD/deps4.txt new file mode 100644 index 000000000..75daccc38 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupD/deps4.txt @@ -0,0 +1 @@ +Dependency 4 diff --git a/buildSrc/src/test/resources/dependencies/groupE/deps5.pom b/buildSrc/src/test/resources/dependencies/groupE/deps5.pom new file mode 100644 index 000000000..370306632 --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupE/deps5.pom @@ -0,0 +1,20 @@ + + 4.0.0 + + groupE + groupE-deps5 + 1 + groupE deps5 + groupE deps5 + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + + + Apache License 2.0 + https://www.apache.org/licenses/LICENSE-2.0 + + + diff --git a/buildSrc/src/test/resources/dependencies/groupE/deps5.txt b/buildSrc/src/test/resources/dependencies/groupE/deps5.txt new file mode 100644 index 000000000..5dc31eaaa --- /dev/null +++ b/buildSrc/src/test/resources/dependencies/groupE/deps5.txt @@ -0,0 +1 @@ +Dependency 5 diff --git a/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.json b/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.json new file mode 100644 index 000000000..7e4c13bb3 --- /dev/null +++ b/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.json @@ -0,0 +1 @@ +{"safeparcel": {"length": 10, "start": 0}, "JSR 305": {"length": 7, "start": 10}} diff --git a/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.txt b/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.txt new file mode 100644 index 000000000..a0203a119 --- /dev/null +++ b/buildSrc/src/test/resources/sampleLicenses/third_party_licenses.txt @@ -0,0 +1 @@ +safeparcelJSR 305 diff --git a/buildSrc/src/test/resources/testDependency.json b/buildSrc/src/test/resources/testDependency.json new file mode 100644 index 000000000..6a9b264eb --- /dev/null +++ b/buildSrc/src/test/resources/testDependency.json @@ -0,0 +1,26 @@ +[ + { + "group": "groupA", + "version": "1", + "fileLocation": "dependencies/groupA/deps1.txt", + "name": "deps1" + }, + { + "group": "groupB", + "version": "2", + "fileLocation": "dependencies/groupB/abc/deps2.txt", + "name": "deps2" + }, + { + "group": "com.google.android.gms", + "version": "3", + "fileLocation": "src/test/resources/dependencies/groupC/deps3.txt", + "name": "deps3" + }, + { + "group": "com.google.firebase", + "version": "4", + "fileLocation": "src/test/resources/dependencies/groupD/deps4.txt", + "name": "deps4" + } +] From f84c133b62607a510fb0318a7eebfd7840bb8187 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:35:17 +0200 Subject: [PATCH 04/58] Mark default variant --- README.md | 5 +++++ app/build.gradle | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cb8efd882..faecffa70 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,11 @@ If you want to use the Google Maps integration, you will need the API keys. You After you've obtained the keys, you will need to copy the file `app/secrets.properties.example` to `app/secrets.properties` and insert the correct keys. +### Build variants + +Hydra comes in two build variants: `store` and `open`. +The `store` variant is the main variant, and used for the Play Store and is the recommended version for most people. The `open` variant only uses open-source software (e.g. OpenStreetMaps instead of Google Maps). Since the open variant contains no crash reporting functionality, crashes from that version not accompanied by a stack trace will not be considered. + ### Useful links - [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/) - [Android Developer Guides](https://developer.android.com/guide/) diff --git a/app/build.gradle b/app/build.gradle index 9d9de7102..cd253c4f9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -45,12 +45,14 @@ android { // Play Store and officially supported version store { + isDefault = true manifestPlaceholders = [ google_maps_key: props.getProperty('MAPS_API_KEY'), ] } open { + ext.enableCrashlytics = false versionNameSuffix "-open" applicationIdSuffix ".open" } @@ -162,7 +164,7 @@ dependencies { testImplementation 'androidx.arch.core:core-testing:2.1.0' testImplementation 'androidx.room:room-testing:2.2.5' // Enable the normal library for unit tests. - testImplementation('org.threeten:threetenbp:1.4.1') { + testImplementation('org.threeten:threetenbp:1.4.2') { exclude group: 'com.jakewharton.threetenabp', module: 'threetenabp' } //noinspection GradleDependency From 486cec191f7604b1f1a9724c5c62c7803ebd9d4a Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:39:00 +0200 Subject: [PATCH 05/58] Add variants to CI --- .github/workflows/android.yml | 27 +++++---------------------- .travis.yml | 6 ++++-- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 5a94984fa..fb5e1c15d 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -9,9 +9,12 @@ on: pull_request: jobs: - build-debug: + test: name: Test debug runs-on: ubuntu-latest + strategy: + matrix: + command: [testOpenDebug, testOpenRelease, testStoreDebug, testStoreRelease] steps: - uses: actions/checkout@v1 - name: Set up JDK 11 @@ -28,24 +31,4 @@ jobs: - name: Test with Gradle uses: eskatos/gradle-command-action@v1 with: - arguments: testDebug - build-release: - name: Test release - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache Gradle files - uses: actions/cache@v1 - with: - path: ~/.gradle/caches - key: release-${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} - restore-keys: | - release-${{ runner.os }}-gradle- - - name: Test with Gradle - uses: eskatos/gradle-command-action@v1 - with: - arguments: testRelease + arguments: ${{ matrix.command }} diff --git a/.travis.yml b/.travis.yml index 7b7106b62..ea4a89581 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,10 @@ jdk: openjdk11 # See https://stackoverflow.com/a/51644855/1831741 for the Java options env: - - COMMAND=testDebug - - COMMAND=testRelease + - COMMAND=testOpenDebug + - COMMAND=testOpenRelease + - COMMAND=testStoreDebug + - COMMAND=testStoreRelease android: components: From 5b27b352d255ea82f4ecd96692165ec4ac9127d5 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:45:39 +0200 Subject: [PATCH 06/58] Rename Github Action --- .github/workflows/android.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index fb5e1c15d..d866754c4 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -10,7 +10,7 @@ on: jobs: test: - name: Test debug + name: Test runs-on: ubuntu-latest strategy: matrix: From ea89f575a110672108977f66830c1dd9aa0458f8 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:55:30 +0200 Subject: [PATCH 07/58] Improve warning message --- app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle b/app/build.gradle index cd253c4f9..d4eaf0ba9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -216,7 +216,7 @@ def loadProperties() { if (actualKeyFile.exists()) { actualKeys.load(actualKeyFile.newReader()) } else { - logger.warn('A secrets.properties file was not found. Maps will not work.') + logger.warn('A secrets.properties file was not found.') } return actualKeys From b53c6de07b41e86fc841f839bb72812244da374d Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 16:55:40 +0200 Subject: [PATCH 08/58] Yeet travis --- .travis.yml | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index ea4a89581..000000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: android -dist: trusty -jdk: openjdk11 - -# See https://stackoverflow.com/a/51644855/1831741 for the Java options -env: - - COMMAND=testOpenDebug - - COMMAND=testOpenRelease - - COMMAND=testStoreDebug - - COMMAND=testStoreRelease - -android: - components: - - tools - - build-tools-29.0.2 - - android-29 - licenses: - - 'android-sdk-preview-license-.+' - - 'android-sdk-license-.+' - - 'google-gdk-license-.+' - -script: - - ./gradlew $COMMAND - -# Caching according to the docs at https://docs.travis-ci.com/user/languages/java/#Projects-Using-Gradle -before_cache: - - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - -# We only build on these branches. -branches: - only: - - master - - development From c9c13510c8b5b46a3ee2c5903f6c13c4140ff3f2 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 17:07:30 +0200 Subject: [PATCH 09/58] Fix caching in GitHub actions --- .github/workflows/android.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index d866754c4..e070f9f26 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -25,9 +25,9 @@ jobs: uses: actions/cache@v1 with: path: ~/.gradle/caches - key: debug-${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + key: ${{ matrix.command }}-${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} restore-keys: | - debug-${{ runner.os }}-gradle- + ${{ matrix.command }}-${{ runner.os }}-gradle- - name: Test with Gradle uses: eskatos/gradle-command-action@v1 with: From 4818ac3a61b8cc8ff6875be2d7ba2362b292f014 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 17:08:30 +0200 Subject: [PATCH 10/58] Replace Travis badge with Github Actions badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index faecffa70..244bba021 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Hydra (Android) [![Build Status](https://travis-ci.org/ZeusWPI/hydra-android.svg?branch=development)](https://travis-ci.org/ZeusWPI/hydra-android) +# Hydra (Android) ![Android CI](https://github.com/ZeusWPI/hydra-android/workflows/Android%20CI/badge.svg?branch=development) Get it on Google Play From 6a24b4995c04ffccfb1b3f4482005ac292ff91b1 Mon Sep 17 00:00:00 2001 From: Niko Strijbol Date: Mon, 30 Mar 2020 23:59:14 +0200 Subject: [PATCH 11/58] Use view binding in activities --- app/build.gradle | 4 + .../be/ugent/zeus/hydra/MainActivity.java | 56 ++++------ .../event/EventDetailsActivity.java | 50 ++++----- .../arch/observers/ProgressObserver.java | 10 +- .../zeus/hydra/common/ui/BaseActivity.java | 35 +++--- .../zeus/hydra/common/ui/WebViewActivity.java | 14 ++- .../preferences/HomeFeedPrefActivity.java | 6 +- .../zeus/hydra/info/InfoSubItemActivity.java | 5 +- .../details/LibraryDetailActivity.java | 90 +++++++--------- .../hydra/preferences/PreferenceActivity.java | 5 +- .../resto/extrafood/ExtraFoodActivity.java | 17 ++- .../hydra/resto/history/HistoryActivity.java | 46 ++++---- .../resto/sandwich/SandwichActivity.java | 18 ++-- .../resto/sandwich/SandwichPagerAdapter.java | 1 + .../zeus/hydra/sko/ArtistDetailsActivity.java | 32 +++--- .../zeus/hydra/sko/OverviewActivity.java | 5 +- .../activity_library_details.xml | 100 ++++++++++-------- .../activity_library_details.xml | 100 ++++++++++-------- .../res/layout/activity_library_details.xml | 4 +- .../res/layout/activity_resto_history.xml | 4 +- app/src/main/res/layout/activity_webview.xml | 10 +- app/src/main/res/layout/x_now_toolbar.xml | 3 +- .../resto/meta/RestoLocationActivity.java | 12 +-- .../res/layout/activity_resto_location.xml | 6 +- 24 files changed, 321 insertions(+), 312 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index d4eaf0ba9..343f5c820 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -39,6 +39,10 @@ android { } } + viewBinding { + enabled = true + } + flavorDimensions "distribution" productFlavors { diff --git a/app/src/main/java/be/ugent/zeus/hydra/MainActivity.java b/app/src/main/java/be/ugent/zeus/hydra/MainActivity.java index 3ec519aac..854691e6b 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/MainActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/MainActivity.java @@ -9,8 +9,6 @@ import android.util.Log; import android.view.MenuItem; import android.view.View; -import android.widget.ProgressBar; - import androidx.annotation.*; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.core.view.GravityCompat; @@ -22,19 +20,19 @@ import java.util.Objects; import be.ugent.zeus.hydra.association.event.list.EventFragment; -import be.ugent.zeus.hydra.news.NewsFragment; import be.ugent.zeus.hydra.common.reporting.Event; import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; +import be.ugent.zeus.hydra.databinding.ActivityMainBinding; import be.ugent.zeus.hydra.feed.HomeFeedFragment; import be.ugent.zeus.hydra.info.InfoFragment; import be.ugent.zeus.hydra.library.list.LibraryListFragment; +import be.ugent.zeus.hydra.news.NewsFragment; import be.ugent.zeus.hydra.onboarding.OnboardingActivity; import be.ugent.zeus.hydra.preferences.PreferenceActivity; import be.ugent.zeus.hydra.resto.menu.RestoFragment; import be.ugent.zeus.hydra.schamper.SchamperFragment; import be.ugent.zeus.hydra.urgent.UrgentFragment; -import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationView; import com.google.android.material.tabs.TabLayout; @@ -153,7 +151,7 @@ * * @see [1] Android Design in Action: Navigation Anti-Patterns, pattern 6 */ -public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener { +public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener { public static final String ARG_TAB = "argTab"; @SuppressWarnings("WeakerAccess") @@ -179,11 +177,7 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig private static final String SHORTCUT_EVENTS = "events"; private static final String SHORTCUT_LIBRARIES = "libraries"; - private DrawerLayout drawer; - private ProgressBar drawerLoader; private ActionBarDrawerToggle toggle; - private NavigationView navigationView; - private AppBarLayout appBarLayout; private boolean isOnboardingOpen; @@ -197,7 +191,7 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); + setContentView(ActivityMainBinding::inflate); if (savedInstanceState != null) { isOnboardingOpen = savedInstanceState.getBoolean(STATE_IS_ONBOARDING_OPEN, false); @@ -220,15 +214,11 @@ protected void onSaveInstanceState(@NonNull Bundle outState) { } private void initialize(@Nullable Bundle savedInstanceState) { - drawer = findViewById(R.id.drawer_layout); - navigationView = findViewById(R.id.navigation_view); - appBarLayout = findViewById(R.id.app_bar_layout); - drawerLoader = findViewById(R.id.drawer_loading); // Register the listener for navigation events from the drawer. - navigationView.setNavigationItemSelectedListener(this); + binding.navigationView.setNavigationItemSelectedListener(this); - toggle = new ActionBarDrawerToggle(this, drawer, findViewById(R.id.toolbar), R.string.action_drawer_open, R.string.action_drawer_close) { + toggle = new ActionBarDrawerToggle(this, binding.drawerLayout, binding.toolbar, R.string.action_drawer_open, R.string.action_drawer_close) { @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, 0); // this disables the animation @@ -240,8 +230,8 @@ public void onDrawerOpened(View drawerView) { Once.markDone(ONCE_DRAWER); } }; - drawer.addDrawerListener(toggle); - drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() { + binding.drawerLayout.addDrawerListener(toggle); + binding.drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerClosed(View drawerView) { // This is used to prevent lag during closing of the navigation drawer. @@ -257,23 +247,23 @@ public void onDrawerClosed(View drawerView) { // If we get a position, use that (for the shortcuts) if (getIntent().hasExtra(ARG_TAB_SHORTCUT)) { int position = getIntent().getIntExtra(ARG_TAB_SHORTCUT, 0); - MenuItem menuItem = navigationView.getMenu().getItem(position); + MenuItem menuItem = binding.navigationView.getMenu().getItem(position); selectDrawerItem(menuItem, NavigationSource.INITIALISATION); } else { // Get start position & select it int start = getIntent().getIntExtra(ARG_TAB, R.id.drawer_feed); - selectDrawerItem(navigationView.getMenu().findItem(start), NavigationSource.INITIALISATION); + selectDrawerItem(binding.navigationView.getMenu().findItem(start), NavigationSource.INITIALISATION); } } else { //Update title, since this is not saved apparently. //Current fragment FragmentManager manager = getSupportFragmentManager(); Fragment current = manager.findFragmentById(R.id.content); - setTitle(navigationView.getMenu().findItem(getFragmentMenuId(current)).getTitle()); + setTitle(binding.navigationView.getMenu().findItem(getFragmentMenuId(current)).getTitle()); } // If this is the first time, open the drawer. if (!Once.beenDone(ONCE_DRAWER)) { - drawer.openDrawer(GravityCompat.START); + binding.drawerLayout.openDrawer(GravityCompat.START); } } @@ -308,13 +298,13 @@ private void selectDrawerItem(MenuItem menuItem, @NavigationSource int navigatio // First check if it are settings, then we don't update anything. if (menuItem.getItemId() == R.id.drawer_pref) { - drawer.closeDrawer(GravityCompat.START); + binding.drawerLayout.closeDrawer(GravityCompat.START); PreferenceActivity.start(this, null); return; } if (menuItem.getItemId() == R.id.drawer_ufora) { - drawer.closeDrawer(GravityCompat.START); + binding.drawerLayout.closeDrawer(GravityCompat.START); Intent launchIntent = getPackageManager().getLaunchIntentForPackage(UFORA); if (launchIntent != null) { startActivity(launchIntent); @@ -379,13 +369,13 @@ private void selectDrawerItem(MenuItem menuItem, @NavigationSource int navigatio // Show the toolbar, in case the new fragment is not scrollable. We must do this before the fragment // begins animating, otherwise glitches can occur. - appBarLayout.setExpanded(true); + binding.appBarLayout.setExpanded(true); - if (drawer.isDrawerOpen(GravityCompat.START)) { + if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) { // Hide the current fragment now, similar to how GMail handles things. if (current != null && current.getView() != null) { current.getView().setVisibility(View.GONE); - drawerLoader.setVisibility(View.VISIBLE); + binding.drawerLoading.progressBar.setVisibility(View.VISIBLE); } // Since there will be a delay, notify the fragment to prevent lingering snackbars or action modes. if (current instanceof ScheduledRemovalListener) { @@ -412,7 +402,7 @@ private void updateDrawer(Fragment fragment, MenuItem item) { Reporting.getTracker(this) .setCurrentScreen(this, item.getTitle().toString(), fragment.getClass().getSimpleName()); // Close the navigation drawer - drawer.closeDrawer(GravityCompat.START); + binding.drawerLayout.closeDrawer(GravityCompat.START); } /** @@ -447,7 +437,7 @@ private void setFragment(Fragment fragment, MenuItem menuItem, @NavigationSource transaction.commitAllowingStateLoss(); // Hide the loader. - drawerLoader.setVisibility(View.GONE); + binding.drawerLoading.progressBar.setVisibility(View.GONE); } /** @@ -457,8 +447,8 @@ private void setFragment(Fragment fragment, MenuItem menuItem, @NavigationSource @Override public void onBackPressed() { // If the drawer is open, close it. - if (drawer.isDrawerOpen(GravityCompat.START)) { - drawer.closeDrawer(GravityCompat.START); + if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) { + binding.drawerLayout.closeDrawer(GravityCompat.START); return; } @@ -470,7 +460,7 @@ public void onBackPressed() { if (current == null) { return; } - MenuItem item = navigationView.getMenu().findItem(getFragmentMenuId(current)); + MenuItem item = binding.navigationView.getMenu().findItem(getFragmentMenuId(current)); updateDrawer(current, item); }; // We need to listen to the back stack to update the drawer. @@ -553,7 +543,7 @@ protected void onNewIntent(Intent intent) { if (intent.hasExtra(ARG_TAB)) { setIntent(intent); int start = intent.getIntExtra(ARG_TAB, R.id.drawer_feed); - selectDrawerItem(navigationView.getMenu().findItem(start), NavigationSource.INNER); + selectDrawerItem(binding.navigationView.getMenu().findItem(start), NavigationSource.INNER); } } diff --git a/app/src/main/java/be/ugent/zeus/hydra/association/event/EventDetailsActivity.java b/app/src/main/java/be/ugent/zeus/hydra/association/event/EventDetailsActivity.java index 0e125d785..6e4ae830a 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/association/event/EventDetailsActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/association/event/EventDetailsActivity.java @@ -5,21 +5,21 @@ import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract; -import androidx.annotation.Nullable; -import androidx.core.text.util.LinkifyCompat; import android.text.util.Linkify; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.LinearLayout; -import android.widget.TextView; import android.widget.Toast; +import androidx.annotation.Nullable; +import androidx.core.text.util.LinkifyCompat; import be.ugent.zeus.hydra.R; -import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.reporting.BaseEvents; +import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; import be.ugent.zeus.hydra.common.utils.NetworkUtils; +import be.ugent.zeus.hydra.databinding.ActivityEventDetailBinding; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import org.threeten.bp.format.DateTimeFormatter; @@ -29,7 +29,7 @@ * * @author Niko Strijbol */ -public class EventDetailsActivity extends BaseActivity { +public class EventDetailsActivity extends BaseActivity { public static final String PARCEL_EVENT = "eventParcelable"; private static final DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); @@ -46,59 +46,51 @@ public static Intent start(Context context, Event event) { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_event_detail); + setContentView(ActivityEventDetailBinding::inflate); //Get data from saved instance, or from intent event = getIntent().getParcelableExtra(PARCEL_EVENT); + assert event != null; - TextView title = findViewById(R.id.title); - TextView location = findViewById(R.id.location); - TextView description = findViewById(R.id.description); - final ImageView organisatorImage = findViewById(R.id.event_organisator_image); - TextView mainName = findViewById(R.id.event_organisator_main); - TextView smallName = findViewById(R.id.event_organisator_small); if (event.getTitle() != null) { - title.setText(event.getTitle()); + binding.title.setText(event.getTitle()); requireToolbar().setTitle(event.getTitle()); } if (event.getAssociation() != null) { - mainName.setText(event.getAssociation().getDisplayName()); - smallName.setText(event.getAssociation().getFullName()); + binding.eventOrganisatorMain.setText(event.getAssociation().getDisplayName()); + binding.eventOrganisatorSmall.setText(event.getAssociation().getFullName()); } if (event.getDescription() != null && !event.getDescription().trim().isEmpty()) { - description.setText(event.getDescription()); - LinkifyCompat.addLinks(description, Linkify.ALL); + binding.description.setText(event.getDescription()); + LinkifyCompat.addLinks(binding.description, Linkify.ALL); } if (event.hasPreciseLocation() || event.hasLocation()) { if (event.hasLocation()) { - location.setText(event.getLocation()); + binding.location.setText(event.getLocation()); } else { - location.setText(getString(R.string.event_detail_precise_location, event.getLatitude(), event.getLongitude())); + binding.location.setText(getString(R.string.event_detail_precise_location, event.getLatitude(), event.getLongitude())); } // Make location clickable - findViewById(R.id.location_row).setOnClickListener(view -> NetworkUtils.maybeLaunchIntent(this, getLocationIntent())); + binding.locationRow.setOnClickListener(view -> NetworkUtils.maybeLaunchIntent(this, getLocationIntent())); } else { - location.setText(R.string.event_detail_no_location); + binding.location.setText(R.string.event_detail_no_location); } - TextView startTime = findViewById(R.id.time_start); - TextView endTime = findViewById(R.id.time_end); - - startTime.setText(event.getLocalStart().format(format)); + binding.timeStart.setText(event.getLocalStart().format(format)); if (event.getLocalEnd() != null) { - endTime.setText(event.getLocalEnd().format(format)); + binding.timeEnd.setText(event.getLocalEnd().format(format)); } else { - endTime.setText(R.string.event_detail_date_unknown); + binding.timeEnd.setText(R.string.event_detail_date_unknown); } if (event.getAssociation() != null) { - Picasso.get().load(event.getAssociation().getImageLink()).into(organisatorImage, new EventCallback(organisatorImage)); + Picasso.get().load(event.getAssociation().getImageLink()).into(binding.eventOrganisatorImage, new EventCallback(binding.eventOrganisatorImage)); } else { - organisatorImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0)); + binding.eventOrganisatorImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0)); } Reporting.getTracker(this) diff --git a/app/src/main/java/be/ugent/zeus/hydra/common/arch/observers/ProgressObserver.java b/app/src/main/java/be/ugent/zeus/hydra/common/arch/observers/ProgressObserver.java index 1d37a40a9..1034c1f71 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/common/arch/observers/ProgressObserver.java +++ b/app/src/main/java/be/ugent/zeus/hydra/common/arch/observers/ProgressObserver.java @@ -1,22 +1,30 @@ package be.ugent.zeus.hydra.common.arch.observers; +import androidx.annotation.NonNull; import androidx.lifecycle.Observer; import androidx.annotation.Nullable; import android.view.View; import android.widget.ProgressBar; import be.ugent.zeus.hydra.common.request.Result; +import be.ugent.zeus.hydra.databinding.XProgressBarBinding; /** + * Observes a progress bar and hides it once the data is loaded. + * * @author Niko Strijbol */ public class ProgressObserver implements Observer> { private final ProgressBar progressBar; - public ProgressObserver(ProgressBar progressBar) { + public ProgressObserver(@NonNull ProgressBar progressBar) { this.progressBar = progressBar; } + public ProgressObserver(@NonNull XProgressBarBinding binding) { + this.progressBar = binding.progressBar; + } + @Override public void onChanged(@Nullable Result result) { if (result == null || result.isDone()) { diff --git a/app/src/main/java/be/ugent/zeus/hydra/common/ui/BaseActivity.java b/app/src/main/java/be/ugent/zeus/hydra/common/ui/BaseActivity.java index d4b740315..addf490e0 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/common/ui/BaseActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/common/ui/BaseActivity.java @@ -1,29 +1,44 @@ package be.ugent.zeus.hydra.common.ui; import android.graphics.drawable.Drawable; +import android.view.LayoutInflater; +import android.view.Menu; import androidx.annotation.ColorInt; -import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; -import androidx.core.graphics.drawable.DrawableCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; -import android.view.Menu; +import androidx.core.app.ActivityCompat; +import androidx.core.graphics.drawable.DrawableCompat; +import androidx.viewbinding.ViewBinding; + +import java9.util.function.Function; import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.utils.ColourUtils; /** * The base activity. Contains code related to common things for almost all activities. + * * Such features include: *
    *
  • Support for the toolbar
  • *
  • Better Google Reporting support
  • + *
  • View binding, see below.
  • *
* + * + *

View binding

+ * + * This activity requires the use of view binding. To set up the view on the + * activity, call {@link #setContentView(Function)}, to which you must pass + * the view binding constructor. + * * @author Niko Strijbol */ -public abstract class BaseActivity extends AppCompatActivity { +public abstract class BaseActivity extends AppCompatActivity { + + protected B binding; /** * Returns the action bar of this activity. If the ActionBar is not present or the method is called at the wrong @@ -42,15 +57,11 @@ public ActionBar requireToolbar() { } } - private Toolbar findToolbar() { - return findViewById(R.id.toolbar); - } - /** * Set the toolbar as action bar, and set it up to have an up button. */ private void setUpActionBar() { - Toolbar toolbar = findToolbar(); + Toolbar toolbar = ActivityCompat.requireViewById(this, R.id.toolbar); setSupportActionBar(toolbar); @@ -60,9 +71,9 @@ private void setUpActionBar() { } } - @Override - public void setContentView(@LayoutRes int layoutResID) { - super.setContentView(layoutResID); + public void setContentView(Function binder) { + this.binding = binder.apply(getLayoutInflater()); + setContentView(this.binding.getRoot()); setUpActionBar(); } diff --git a/app/src/main/java/be/ugent/zeus/hydra/common/ui/WebViewActivity.java b/app/src/main/java/be/ugent/zeus/hydra/common/ui/WebViewActivity.java index 32972a7b6..28e8dba3d 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/common/ui/WebViewActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/common/ui/WebViewActivity.java @@ -10,13 +10,14 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.network.InterceptingWebViewClient; +import be.ugent.zeus.hydra.databinding.ActivityWebviewBinding; /** * Displays a web view. * * @author Niko Strijbol */ -public class WebViewActivity extends BaseActivity { +public class WebViewActivity extends BaseActivity { public static final String URL = "be.ugent.zeus.hydra.url"; public static final String TITLE = "be.ugent.zeus.hydra.title"; @@ -25,13 +26,10 @@ public class WebViewActivity extends BaseActivity { @SuppressLint("SetJavaScriptEnabled") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_webview); + setContentView(ActivityWebviewBinding::inflate); - WebView webView = findViewById(R.id.web_view); - ProgressBar progressBar = findViewById(R.id.progress_bar); - - webView.getSettings().setJavaScriptEnabled(true); - webView.setWebViewClient(new ProgressClient(progressBar, this)); + binding.webView.getSettings().setJavaScriptEnabled(true); + binding.webView.setWebViewClient(new ProgressClient(binding.progressBar.progressBar, this)); Intent intent = getIntent(); String url = intent.getStringExtra(URL); @@ -41,7 +39,7 @@ protected void onCreate(Bundle savedInstanceState) { getSupportActionBar().setTitle(title); } - webView.loadUrl(url); + binding.webView.loadUrl(url); } private static class ProgressClient extends InterceptingWebViewClient { diff --git a/app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedPrefActivity.java b/app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedPrefActivity.java index cfe1969c0..df7e9231a 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedPrefActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedPrefActivity.java @@ -5,8 +5,8 @@ import android.os.Parcelable; import androidx.annotation.Nullable; -import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.ui.BaseActivity; +import be.ugent.zeus.hydra.databinding.ActivityPreferencesBinding; import be.ugent.zeus.hydra.preferences.PreferenceActivity; import be.ugent.zeus.hydra.preferences.PreferenceEntry; @@ -15,12 +15,12 @@ * * @author Niko Strijbol */ -public class HomeFeedPrefActivity extends BaseActivity { +public class HomeFeedPrefActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_preferences_homefeed); + setContentView(ActivityPreferencesBinding::inflate); } @Override diff --git a/app/src/main/java/be/ugent/zeus/hydra/info/InfoSubItemActivity.java b/app/src/main/java/be/ugent/zeus/hydra/info/InfoSubItemActivity.java index 9476783a3..86dedb2e6 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/info/InfoSubItemActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/info/InfoSubItemActivity.java @@ -5,10 +5,11 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.ui.BaseActivity; +import be.ugent.zeus.hydra.databinding.ActivityInfoSubItemBinding; import java.util.ArrayList; -public class InfoSubItemActivity extends BaseActivity { +public class InfoSubItemActivity extends BaseActivity { public static final String INFO_TITLE = "be.ugent.zeus.hydra.infoTitle"; public static final String INFO_ITEMS = "be.ugent.zeus.hydra.infoItems"; @@ -16,7 +17,7 @@ public class InfoSubItemActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_info_sub_item); + setContentView(ActivityInfoSubItemBinding::inflate); // Display the fragment as the main content. InfoFragment fragment = new InfoFragment(); diff --git a/app/src/main/java/be/ugent/zeus/hydra/library/details/LibraryDetailActivity.java b/app/src/main/java/be/ugent/zeus/hydra/library/details/LibraryDetailActivity.java index cf5b8303d..2731d4ed1 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/library/details/LibraryDetailActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/library/details/LibraryDetailActivity.java @@ -12,7 +12,9 @@ import android.view.Menu; import android.view.MenuItem; import android.view.View; -import android.widget.*; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; @@ -34,14 +36,14 @@ import be.ugent.zeus.hydra.common.reporting.Event; import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; -import be.ugent.zeus.hydra.common.utils.ViewUtils; import be.ugent.zeus.hydra.common.ui.html.Utils; +import be.ugent.zeus.hydra.common.utils.DateUtils; +import be.ugent.zeus.hydra.common.utils.NetworkUtils; +import be.ugent.zeus.hydra.common.utils.ViewUtils; +import be.ugent.zeus.hydra.databinding.ActivityLibraryDetailsBinding; import be.ugent.zeus.hydra.library.Library; import be.ugent.zeus.hydra.library.favourites.FavouritesRepository; import be.ugent.zeus.hydra.library.favourites.LibraryFavourite; -import be.ugent.zeus.hydra.common.utils.DateUtils; -import be.ugent.zeus.hydra.common.utils.NetworkUtils; -import com.google.android.material.appbar.CollapsingToolbarLayout; import com.google.android.material.snackbar.Snackbar; import com.squareup.picasso.Picasso; import net.cachapa.expandablelayout.ExpandableLayout; @@ -51,16 +53,13 @@ * * @author Niko Strijbol */ -public class LibraryDetailActivity extends BaseActivity { +public class LibraryDetailActivity extends BaseActivity { public static final String ARG_LIBRARY = "argLibrary"; private static final String TAG = "LibraryDetailActivity"; private Library library; - private Button button; - private Button expandButton; - private FrameLayout layout; public static void launchActivity(Context context, Library library) { Intent intent = new Intent(context, LibraryDetailActivity.class); @@ -71,90 +70,79 @@ public static void launchActivity(Context context, Library library) { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_library_details); + setContentView(ActivityLibraryDetailsBinding::inflate); library = getIntent().getParcelableExtra(ARG_LIBRARY); - layout = findViewById(R.id.frame_layout); - ImageView header = findViewById(R.id.header_image); - Picasso.get().load(library.getHeaderImage(this)).into(header); + Picasso.get().load(library.getHeaderImage(this)).into(binding.headerImage); - CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar); - collapsingToolbarLayout.setTitle(library.getName()); + binding.collapsingToolbar.setTitle(library.getName()); // TODO: why is this necessary? int white = ContextCompat.getColor(this, R.color.white); - collapsingToolbarLayout.setExpandedTitleColor(white); - collapsingToolbarLayout.setCollapsedTitleTextColor(white); + binding.collapsingToolbar.setExpandedTitleColor(white); + binding.collapsingToolbar.setCollapsedTitleTextColor(white); String address = makeFullAddressText(); if (TextUtils.isEmpty(address)) { - findViewById(R.id.library_address_card).setVisibility(View.GONE); + binding.libraryAddressCard.setVisibility(View.GONE); } else { - TextView textView = findViewById(R.id.library_address); - textView.setText(makeFullAddressText()); - textView.setOnClickListener(v -> NetworkUtils.maybeLaunchIntent(LibraryDetailActivity.this, mapsIntent())); + binding.libraryAddress.setText(makeFullAddressText()); + binding.libraryAddress.setOnClickListener(v -> NetworkUtils.maybeLaunchIntent(LibraryDetailActivity.this, mapsIntent())); } final ViewModelProvider provider = new ViewModelProvider(this); - button = findViewById(R.id.library_favourite); FavouriteViewModel viewModel = provider.get(FavouriteViewModel.class); viewModel.setLibrary(library); viewModel.getData().observe(this, isFavourite -> { Drawable drawable; Context c = LibraryDetailActivity.this; if (isFavourite) { - button.setSelected(true); + binding.libraryFavourite.setSelected(true); drawable = ViewUtils.getTintedVectorDrawableAttr(c, R.drawable.ic_star, R.attr.colorSecondary); } else { drawable = ViewUtils.getTintedVectorDrawableAttr(c, R.drawable.ic_star, R.attr.colorPrimary); - button.setSelected(false); + binding.libraryFavourite.setSelected(false); } - button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null); + binding.libraryFavourite.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null); }); - button.setOnClickListener(v -> updateStatus(library, button.isSelected())); + binding.libraryFavourite.setOnClickListener(v -> updateStatus(library, binding.libraryFavourite.isSelected())); - ExpandableLayout layout = findViewById(R.id.expandable_layout); - expandButton = findViewById(R.id.expand_button); - expandButton.setOnClickListener(v -> layout.toggle()); + binding.expandButton.setOnClickListener(v -> binding.expandableLayout.toggle()); - layout.setOnExpansionUpdateListener((value, state) -> { + binding.expandableLayout.setOnExpansionUpdateListener((value, state) -> { if (state == ExpandableLayout.State.COLLAPSED) { - expandButton.setText(R.string.library_more); + binding.expandButton.setText(R.string.library_more); } else if (state == ExpandableLayout.State.EXPANDED) { - expandButton.setText(R.string.library_less); + binding.expandButton.setText(R.string.library_less); } }); - TextView remarks = findViewById(R.id.library_remarks); String comments = library.getCommentsAsString(); if (TextUtils.isEmpty(comments)) { - remarks.setVisibility(View.GONE); - findViewById(R.id.library_remarks_divider).setVisibility(View.GONE); - findViewById(R.id.library_remarks_title).setVisibility(View.GONE); + binding.libraryRemarks.setVisibility(View.GONE); + binding.libraryRemarksDivider.setVisibility(View.GONE); + binding.libraryRemarksTitle.setVisibility(View.GONE); } else { - remarks.setText(Utils.fromHtml(comments)); - layout.setExpanded(true, false); + binding.libraryRemarks.setText(Utils.fromHtml(comments)); + binding.expandableLayout.setExpanded(true, false); } - TextView email = findViewById(R.id.library_mail_row_text); - email.setText(library.getEmail()); - LinkifyCompat.addLinks(email, Linkify.EMAIL_ADDRESSES); - TextView phone = findViewById(R.id.library_phone_row_text); + binding.libraryMailRowText.setText(library.getEmail()); + LinkifyCompat.addLinks(binding.libraryMailRowText, Linkify.EMAIL_ADDRESSES); String phoneString = library.getPhones(); if (TextUtils.isEmpty(phoneString)) { - phone.setText(R.string.library_detail_no_phone); + binding.libraryPhoneRowText.setText(R.string.library_detail_no_phone); } else { - phone.setText(phoneString); - LinkifyCompat.addLinks(phone, Linkify.PHONE_NUMBERS); + binding.libraryPhoneRowText.setText(phoneString); + LinkifyCompat.addLinks(binding.libraryPhoneRowText, Linkify.PHONE_NUMBERS); } - TextView contact = findViewById(R.id.library_contact_row_text); - contact.setText(library.getContact()); + binding.libraryContactRowText.setText(library.getContact()); HoursViewModel model = provider.get(HoursViewModel.class); model.setLibrary(library); model.getData().observe(this, PartialErrorObserver.with(this::onError)); - model.getData().observe(this, new ProgressObserver<>(findViewById(R.id.progress_bar))); + model.getData().observe(this, new ProgressObserver<>(binding.progressBar)); model.getData().observe(this, SuccessObserver.with(this::receiveData)); Reporting.getTracker(this).log(new LibraryViewEvent(library)); @@ -175,7 +163,7 @@ private void updateStatus(Library library, boolean isSelected) { protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); // Save the toggle button state. - outState.putString("button", String.valueOf(expandButton.getText())); + outState.putString("button", String.valueOf(binding.expandButton.getText())); } @Override @@ -183,7 +171,7 @@ protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore the toggle button state. if (savedInstanceState.get("button") != null) { - expandButton.setText(savedInstanceState.getString("button")); + binding.expandButton.setText(savedInstanceState.getString("button")); } } @@ -221,7 +209,7 @@ private void receiveData(List list) { tableLayout.addView(tableRow); } - layout.addView(tableLayout); + binding.frameLayout.addView(tableLayout); } @Override diff --git a/app/src/main/java/be/ugent/zeus/hydra/preferences/PreferenceActivity.java b/app/src/main/java/be/ugent/zeus/hydra/preferences/PreferenceActivity.java index f2b36fd9e..c009a5c30 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/preferences/PreferenceActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/preferences/PreferenceActivity.java @@ -11,13 +11,14 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.ui.BaseActivity; +import be.ugent.zeus.hydra.databinding.ActivityPreferencesBinding; /** * Activity that will show a fragment. * * @author Niko Strijbol */ -public class PreferenceActivity extends BaseActivity { +public class PreferenceActivity extends BaseActivity { /** * Argument for the activity, indicating which fragment should be shown. @@ -40,7 +41,7 @@ public static void start(@NonNull Context context, @Nullable PreferenceEntry ent @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_preferences); + setContentView(ActivityPreferencesBinding::inflate); if (savedInstanceState != null) { // If a specific screen is requested, use that one. diff --git a/app/src/main/java/be/ugent/zeus/hydra/resto/extrafood/ExtraFoodActivity.java b/app/src/main/java/be/ugent/zeus/hydra/resto/extrafood/ExtraFoodActivity.java index 63d660396..e5950223c 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/resto/extrafood/ExtraFoodActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/resto/extrafood/ExtraFoodActivity.java @@ -10,28 +10,25 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; +import be.ugent.zeus.hydra.databinding.ActivityExtraFoodBinding; import com.google.android.material.tabs.TabLayout; -public class ExtraFoodActivity extends BaseActivity { +public class ExtraFoodActivity extends BaseActivity { private ExtraFoodViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_extra_food); - - TabLayout tabLayout = findViewById(R.id.tab_layout); - ViewPager viewPager = findViewById(R.id.pager); + setContentView(ActivityExtraFoodBinding::inflate); ExtraFoodPagerAdapter adapter = new ExtraFoodPagerAdapter(getSupportFragmentManager(), this); - viewPager.setAdapter(adapter); - tabLayout.setupWithViewPager(viewPager); - viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { + binding.pager.setAdapter(adapter); + binding.tabLayout.setupWithViewPager(binding.pager); + binding.pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { - //noinspection ConstantConditions - Reporting.getTracker(getApplicationContext()) + Reporting.getTracker(ExtraFoodActivity.this) .setCurrentScreen( ExtraFoodActivity.this, adapter.getPageTitle(position).toString(), diff --git a/app/src/main/java/be/ugent/zeus/hydra/resto/history/HistoryActivity.java b/app/src/main/java/be/ugent/zeus/hydra/resto/history/HistoryActivity.java index ae1a7b3de..d1caca73e 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/resto/history/HistoryActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/resto/history/HistoryActivity.java @@ -4,9 +4,10 @@ import android.os.Bundle; import android.util.Log; import android.view.View; -import android.widget.*; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.DatePicker; import androidx.annotation.NonNull; -import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.ViewModelProvider; @@ -20,17 +21,20 @@ import be.ugent.zeus.hydra.common.network.IOFailureException; import be.ugent.zeus.hydra.common.ui.BaseActivity; import be.ugent.zeus.hydra.common.ui.NoPaddingArrayAdapter; +import be.ugent.zeus.hydra.common.utils.DateUtils; +import be.ugent.zeus.hydra.databinding.ActivityRestoHistoryBinding; import be.ugent.zeus.hydra.resto.RestoChoice; import be.ugent.zeus.hydra.resto.RestoMenu; import be.ugent.zeus.hydra.resto.SingleDayFragment; import be.ugent.zeus.hydra.resto.meta.selectable.SelectableMetaViewModel; import be.ugent.zeus.hydra.resto.meta.selectable.SelectedResto; -import be.ugent.zeus.hydra.common.utils.DateUtils; import org.threeten.bp.LocalDate; import org.threeten.bp.Month; import org.threeten.bp.ZoneId; -public class HistoryActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener { +public class HistoryActivity + extends BaseActivity + implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener { private static final String ARG_DATE = "arg_date"; @@ -39,15 +43,12 @@ public class HistoryActivity extends BaseActivity implements DatePickerDialog.On private LocalDate localDate; private RestoChoice restoChoice; private SingleDayViewModel viewModel; - private Spinner restoSpinner; - private ProgressBar restoProgressBar; private ArrayAdapter restoAdapter; - private TextView errorView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_resto_history); + setContentView(ActivityRestoHistoryBinding::inflate); if (savedInstanceState != null && savedInstanceState.containsKey(ARG_DATE)) { localDate = (LocalDate) savedInstanceState.getSerializable(ARG_DATE); @@ -57,32 +58,27 @@ protected void onCreate(Bundle savedInstanceState) { localDate = LocalDate.now(); } - Toolbar bottomToolbar = findViewById(R.id.bottom_toolbar); - - restoSpinner = findViewById(R.id.resto_spinner); - restoSpinner.setEnabled(false); - restoProgressBar = findViewById(R.id.resto_progress_bar); - restoAdapter = new NoPaddingArrayAdapter<>(bottomToolbar.getContext(), R.layout.x_spinner_title_resto); + binding.restoSpinner.setEnabled(false); + restoAdapter = new NoPaddingArrayAdapter<>(binding.bottomToolbar.getContext(), R.layout.x_spinner_title_resto); restoAdapter.add(new SelectedResto.Wrapper(getString(R.string.resto_spinner_loading))); restoAdapter.setDropDownViewResource(R.layout.x_simple_spinner_dropdown_item); - restoSpinner.setAdapter(restoAdapter); + binding.restoSpinner.setAdapter(restoAdapter); final ViewModelProvider provider = new ViewModelProvider(this); - errorView = findViewById(R.id.error_view); viewModel = provider.get(SingleDayViewModel.class); viewModel.changeDate(localDate); // Set the initial date viewModel.getData().observe(this, new SuccessObserver() { @Override protected void onSuccess(@NonNull RestoMenu data) { // Add the fragment - errorView.setVisibility(View.GONE); + binding.errorView.setVisibility(View.GONE); setTitle(getString(R.string.resto_history_title, DateUtils.getFriendlyDate(HistoryActivity.this, data.getDate()))); showFragment(data); } }); viewModel.getData().observe(this, PartialErrorObserver.with(this::onError)); - viewModel.getData().observe(this, new ProgressObserver<>(findViewById(R.id.progress_bar))); + viewModel.getData().observe(this, new ProgressObserver<>(binding.progressBar)); SelectableMetaViewModel metaViewModel = provider.get(SelectableMetaViewModel.class); metaViewModel.getData().observe(this, SuccessObserver.with(this::onReceiveRestos)); @@ -112,11 +108,11 @@ private void onError(Throwable throwable) { Log.w(TAG, "Error", throwable); hideFragment(); setTitle(R.string.resto_history_error); - errorView.setVisibility(View.VISIBLE); + binding.errorView.setVisibility(View.VISIBLE); if (throwable instanceof IOFailureException) { - errorView.setText(R.string.error_network); + binding.errorView.setText(R.string.error_network); } else { - errorView.setText(getString(R.string.resto_history_not_found, DateUtils.getFriendlyDate(this, localDate))); + binding.errorView.setText(getString(R.string.resto_history_not_found, DateUtils.getFriendlyDate(this, localDate))); } } @@ -129,10 +125,10 @@ private void onReceiveRestos(List choices) { List wrappers = selectedResto.getAsWrappers(); restoAdapter.clear(); restoAdapter.addAll(wrappers); - restoSpinner.setSelection(selectedResto.getSelectedIndex(), false); - restoSpinner.setEnabled(true); - restoProgressBar.setVisibility(View.GONE); - restoSpinner.setOnItemSelectedListener(this); + binding.restoSpinner.setSelection(selectedResto.getSelectedIndex(), false); + binding.restoSpinner.setEnabled(true); + binding.restoProgressBar.setVisibility(View.GONE); + binding.restoSpinner.setOnItemSelectedListener(this); } private DatePickerDialog createAndSetupDialog() { diff --git a/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichActivity.java b/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichActivity.java index 43f489a1f..565d8637f 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichActivity.java @@ -8,32 +8,28 @@ import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; -import be.ugent.zeus.hydra.resto.extrafood.FoodFragment; import be.ugent.zeus.hydra.common.utils.NetworkUtils; -import com.google.android.material.tabs.TabLayout; +import be.ugent.zeus.hydra.databinding.ActivityExtraFoodBinding; +import be.ugent.zeus.hydra.resto.extrafood.FoodFragment; /** * Activity for the sandwiches. */ -public class SandwichActivity extends BaseActivity { +public class SandwichActivity extends BaseActivity{ public static final String URL = "https://www.ugent.be/student/nl/meer-dan-studeren/resto/broodjes"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_extra_food); - - TabLayout tabLayout = findViewById(R.id.tab_layout); - ViewPager viewPager = findViewById(R.id.pager); + setContentView(ActivityExtraFoodBinding::inflate); SandwichPagerAdapter adapter = new SandwichPagerAdapter(getSupportFragmentManager(), this); - viewPager.setAdapter(adapter); - tabLayout.setupWithViewPager(viewPager); - viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { + binding.pager.setAdapter(adapter); + binding.tabLayout.setupWithViewPager(binding.pager); + binding.pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { - //noinspection ConstantConditions Reporting.getTracker(getApplicationContext()) .setCurrentScreen( SandwichActivity.this, diff --git a/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichPagerAdapter.java b/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichPagerAdapter.java index e48976aa7..7dd7e338e 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichPagerAdapter.java +++ b/app/src/main/java/be/ugent/zeus/hydra/resto/sandwich/SandwichPagerAdapter.java @@ -40,6 +40,7 @@ public Fragment getItem(int position) { } @Override + @NonNull public CharSequence getPageTitle(int position) { @StringRes int string; switch (position) { diff --git a/app/src/main/java/be/ugent/zeus/hydra/sko/ArtistDetailsActivity.java b/app/src/main/java/be/ugent/zeus/hydra/sko/ArtistDetailsActivity.java index 10db75ed4..8e077f749 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/sko/ArtistDetailsActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/sko/ArtistDetailsActivity.java @@ -8,9 +8,7 @@ import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; -import android.widget.ImageView; -import android.widget.TextView; - +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import be.ugent.zeus.hydra.R; @@ -19,6 +17,7 @@ import be.ugent.zeus.hydra.common.reporting.Reporting; import be.ugent.zeus.hydra.common.ui.BaseActivity; import be.ugent.zeus.hydra.common.utils.NetworkUtils; +import be.ugent.zeus.hydra.databinding.ActivitySkoArtistBinding; import com.squareup.picasso.Picasso; /** @@ -26,13 +25,14 @@ * * @author Niko Strijbol */ -public class ArtistDetailsActivity extends BaseActivity { +public class ArtistDetailsActivity extends BaseActivity { private static final String PARCEL_ARTIST = "artist"; private Artist artist; - public static Intent start(Context context, Artist artist) { + @NonNull + public static Intent start(@NonNull Context context, @NonNull Artist artist) { Intent intent = new Intent(context, ArtistDetailsActivity.class); intent.putExtra(PARCEL_ARTIST, artist); return intent; @@ -41,38 +41,34 @@ public static Intent start(Context context, Artist artist) { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_sko_artist); + setContentView(ActivitySkoArtistBinding::inflate); Intent intent = getIntent(); artist = intent.getParcelableExtra(PARCEL_ARTIST); + assert artist != null; - TextView title = findViewById(R.id.title); - TextView date = findViewById(R.id.date); - TextView content = findViewById(R.id.content); - ImageView headerImage = findViewById(R.id.header_image); - - title.setText(artist.getName()); + binding.title.setText(artist.getName()); setTitle(artist.getName()); if (artist.getImage() != null) { - Picasso.get().load(artist.getImage()).fit().centerInside().into(headerImage); + Picasso.get().load(artist.getImage()).fit().centerInside().into(binding.headerImage); } - date.setText(artist.getDisplayDate(this)); + binding.date.setText(artist.getDisplayDate(this)); if (!TextUtils.isEmpty(artist.getDescription())) { - content.setText(artist.getDescription()); + binding.content.setText(artist.getDescription()); } else { - content.setText(R.string.sko_artist_no_content); + binding.content.setText(R.string.sko_artist_no_content); } - findViewById(R.id.sko_artist_search_web).setOnClickListener(view -> { + binding.skoArtistSearchWeb.setOnClickListener(view -> { Intent searchIntent = new Intent(Intent.ACTION_WEB_SEARCH); searchIntent.putExtra(SearchManager.QUERY, artist.getName()); NetworkUtils.maybeLaunchIntent(ArtistDetailsActivity.this, searchIntent); }); - findViewById(R.id.sko_artist_search_music).setOnClickListener(view -> { + binding.skoArtistSearchMusic.setOnClickListener(view -> { Intent musicIntent = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH); musicIntent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE); musicIntent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist.getName()); diff --git a/app/src/main/java/be/ugent/zeus/hydra/sko/OverviewActivity.java b/app/src/main/java/be/ugent/zeus/hydra/sko/OverviewActivity.java index 381048b02..7ff8bb7c7 100644 --- a/app/src/main/java/be/ugent/zeus/hydra/sko/OverviewActivity.java +++ b/app/src/main/java/be/ugent/zeus/hydra/sko/OverviewActivity.java @@ -12,13 +12,14 @@ import be.ugent.zeus.hydra.common.network.Endpoints; import be.ugent.zeus.hydra.common.ui.BaseActivity; import be.ugent.zeus.hydra.common.utils.NetworkUtils; +import be.ugent.zeus.hydra.databinding.ActivitySkoMainBinding; /** * SKO overview activity. Only displays the line-up. * * @author Niko Strijbol */ -public class OverviewActivity extends BaseActivity { +public class OverviewActivity extends BaseActivity { private static final String SKO_WEBSITE = Endpoints.SKO; @@ -36,7 +37,7 @@ public static Intent start(Context context) { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_sko_main); + setContentView(ActivitySkoMainBinding::inflate); } @Override diff --git a/app/src/main/res/layout-sw600dp-land/activity_library_details.xml b/app/src/main/res/layout-sw600dp-land/activity_library_details.xml index 10a9c7f91..15f44d8bd 100644 --- a/app/src/main/res/layout-sw600dp-land/activity_library_details.xml +++ b/app/src/main/res/layout-sw600dp-land/activity_library_details.xml @@ -1,6 +1,5 @@ - + android:contentDescription="@string/content_desc_library" /> + android:contentDescription="@string/content_desc_library" /> - - - + style="?textAppearanceBody2" + android:paddingBottom="@dimen/card_text_padding_bottom" + android:focusable="true" + tools:ignore="UnusedAttribute" /> - + -