diff --git a/RepositoryPattern/README.md b/RepositoryPattern/README.md new file mode 100755 index 000000000..7fd7b8432 --- /dev/null +++ b/RepositoryPattern/README.md @@ -0,0 +1,54 @@ +DevByteRepository - Solution Code +================================== + +Solution code for the Repository codelab. + +Introduction +------------ + +DevByteRepository app displays a list of DevByte videos. DevByte videos are +short videos made by the Google Android developer relations team to introduce +new developer features on Android. This app demonstrates the Repository pattern, +the recommended best practice for code separation and architecture. Using +repository pattern the data layer is abstracted from the rest of the app. +Repositories act as mediators between different data sources, such as persistent +models, web services, and caches and the rest of the app. + +Pre-requisites +-------------- + +You need to know: +- How to open, build, and run Android apps with Android Studio. +- The basic Android Architecture Components, ViewModel, and LiveData. +- The data persistence library, Room. +- Building and launching a coroutine. +- Read the logs using the Logcat. +- Binding adapters in data binding. +- Using the Retrofit networking library. + + +Getting Started +--------------- + +1. Download and run the app. +2. You need Android Studio 3.4 or higher to build this project. + +License +------- + +Copyright 2019 Google, Inc. + +Licensed to the Apache Software Foundation (ASF) under one or more contributor +license agreements. See the NOTICE file distributed with this work for +additional information regarding copyright ownership. The ASF licenses this +file to you under the Apache License, Version 2.0 (the "License"); you may not +use this file except in compliance with the License. You may obtain a copy of +the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations under +the License. diff --git a/RepositoryPattern/app/build.gradle b/RepositoryPattern/app/build.gradle new file mode 100755 index 000000000..898f336ae --- /dev/null +++ b/RepositoryPattern/app/build.gradle @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' +apply plugin: "androidx.navigation.safeargs" +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 32 + defaultConfig { + applicationId "com.example.android.devbyteviewer" + minSdkVersion 19 + targetSdkVersion 32 + versionCode 1 + versionName "1.0" + vectorDrawables.useSupportLibrary = true + multiDexEnabled true + } + buildTypes { + release { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + buildFeatures { + dataBinding true + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8.toString() + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + + // support libraries + implementation 'androidx.appcompat:appcompat:1.4.1' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation 'com.google.android.material:material:1.5.0' + + // Android KTX + implementation 'androidx.core:core-ktx:1.7.0' + + // constraint layout + implementation 'androidx.constraintlayout:constraintlayout:2.1.3' + + // navigation + def nav_version = "1.0.0" + implementation "android.arch.navigation:navigation-fragment-ktx:$nav_version" + implementation "android.arch.navigation:navigation-ui-ktx:$nav_version" + + // coroutines for getting off the UI thread + def coroutines = "1.6.0" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines" + + // retrofit for networking + implementation 'com.squareup.retrofit2:retrofit:2.9.0' + implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2' + implementation 'com.squareup.retrofit2:converter-moshi:2.9.0' + + // moshi for parsing the JSON format + def moshi_version = "1.13.0" + implementation "com.squareup.moshi:moshi:$moshi_version" + implementation "com.squareup.moshi:moshi-kotlin:$moshi_version" + kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version" + + // joda time library for dealing with time + implementation 'joda-time:joda-time:2.10' + + // arch components + // ViewModel and LiveData + def lifecycle_version = "2.4.1" +// implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" + implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" + + // logging + implementation 'com.jakewharton.timber:timber:4.7.1' + + // glide for images + implementation 'com.github.bumptech.glide:glide:4.8.0' + kapt 'com.github.bumptech.glide:compiler:4.7.1' + + // Room dependency + def room_version = "2.4.1" + implementation "androidx.room:room-runtime:$room_version" + kapt "androidx.room:room-compiler:$room_version" + +} diff --git a/RepositoryPattern/app/proguard-rules.pro b/RepositoryPattern/app/proguard-rules.pro new file mode 100755 index 000000000..f1b424510 --- /dev/null +++ b/RepositoryPattern/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/RepositoryPattern/app/src/main/AndroidManifest.xml b/RepositoryPattern/app/src/main/AndroidManifest.xml new file mode 100755 index 000000000..965af5a18 --- /dev/null +++ b/RepositoryPattern/app/src/main/AndroidManifest.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/DevByteApplication.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/DevByteApplication.kt new file mode 100755 index 000000000..7f32bbfdd --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/DevByteApplication.kt @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer + +import android.app.Application +import timber.log.Timber + +/** + * Override application to setup background work via WorkManager + */ +class DevByteApplication : Application() { + + /** + * onCreate is called before the first screen is shown to the user. + * + * Use it to setup any background tasks, running expensive setup operations in a background + * thread to avoid delaying app start. + */ + override fun onCreate() { + super.onCreate() + Timber.plant(Timber.DebugTree()) + } +} diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/DatabaseEntities.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/DatabaseEntities.kt new file mode 100755 index 000000000..c5f5440f1 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/DatabaseEntities.kt @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.database + +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.example.android.devbyteviewer.domain.DevByteVideo + + +/** + * Database entities go in this file. These are responsible for reading and writing from the + * database. + */ + + +/** + * DatabaseVideo represents a video entity in the database. + */ +@Entity +data class DatabaseVideo constructor( + @PrimaryKey + val url: String, + val updated: String, + val title: String, + val description: String, + val thumbnail: String) + + +/** + * Map DatabaseVideos to domain entities + */ +fun List.asDomainModel(): List { + return map { + DevByteVideo( + url = it.url, + title = it.title, + description = it.description, + updated = it.updated, + thumbnail = it.thumbnail) + } +} diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/Room.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/Room.kt new file mode 100755 index 000000000..be12dcd92 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/database/Room.kt @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.database + +import android.content.Context +import androidx.lifecycle.LiveData +import androidx.room.* + +@Dao +interface VideoDao { + @Query("select * from databasevideo") + fun getVideos(): LiveData> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertAll( videos: List) +} + + + +@Database(entities = [DatabaseVideo::class], version = 1) +abstract class VideosDatabase: RoomDatabase() { + abstract val videoDao: VideoDao +} + +private lateinit var INSTANCE: VideosDatabase + +fun getDatabase(context: Context): VideosDatabase { + synchronized(VideosDatabase::class.java) { + if (!::INSTANCE.isInitialized) { + INSTANCE = Room.databaseBuilder(context.applicationContext, + VideosDatabase::class.java, + "videos").build() + } + } + return INSTANCE +} diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/domain/Models.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/domain/Models.kt new file mode 100755 index 000000000..b7d5169b8 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/domain/Models.kt @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.domain + +import com.example.android.devbyteviewer.util.smartTruncate + +/** + * Domain objects are plain Kotlin data classes that represent the things in our app. These are the + * objects that should be displayed on screen, or manipulated by the app. + * + * @see database for objects that are mapped to the database + * @see network for objects that parse or prepare network calls + */ + +/** + * Videos represent a devbyte that can be played. + */ +data class DevByteVideo(val title: String, + val description: String, + val url: String, + val updated: String, + val thumbnail: String) { + + /** + * Short description is used for displaying truncated descriptions in the UI + */ + val shortDescription: String + get() = description.smartTruncate(200) +} \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/DataTransferObjects.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/DataTransferObjects.kt new file mode 100755 index 000000000..d0dcfb5a6 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/DataTransferObjects.kt @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.network + +import com.example.android.devbyteviewer.database.DatabaseVideo +import com.example.android.devbyteviewer.domain.DevByteVideo +import com.squareup.moshi.JsonClass + +/** + * DataTransferObjects go in this file. These are responsible for parsing responses from the server + * or formatting objects to send to the server. You should convert these to domain objects before + * using them. + * + * @see domain package for + */ + +/** + * VideoHolder holds a list of Videos. + * + * This is to parse first level of our network result which looks like + * + * { + * "videos": [] + * } + */ +@JsonClass(generateAdapter = true) +data class NetworkVideoContainer(val videos: List) + +/** + * Videos represent a devbyte that can be played. + */ +@JsonClass(generateAdapter = true) +data class NetworkVideo( + val title: String, + val description: String, + val url: String, + val updated: String, + val thumbnail: String, + val closedCaptions: String?) + +/** + * Convert Network results to database objects + */ +fun NetworkVideoContainer.asDomainModel(): List { + return videos.map { + DevByteVideo( + title = it.title, + description = it.description, + url = it.url, + updated = it.updated, + thumbnail = it.thumbnail) + } +} + + +/** + * Convert Network results to database objects + */ +fun NetworkVideoContainer.asDatabaseModel(): List { + return videos.map { + DatabaseVideo( + title = it.title, + description = it.description, + url = it.url, + updated = it.updated, + thumbnail = it.thumbnail) + } +} + diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/Service.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/Service.kt new file mode 100755 index 000000000..80d165873 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/network/Service.kt @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.network + +import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory +import kotlinx.coroutines.Deferred +import retrofit2.Retrofit +import retrofit2.converter.moshi.MoshiConverterFactory +import retrofit2.http.GET + +// Since we only have one service, this can all go in one file. +// If you add more services, split this to multiple files and make sure to share the retrofit +// object between services. + +/** + * A retrofit service to fetch a devbyte playlist. + */ +interface DevbyteService { + @GET("devbytes") + suspend fun getPlaylist(): NetworkVideoContainer +} + +/** + * Main entry point for network access. Call like `DevByteNetwork.devbytes.getPlaylist()` + */ +object DevByteNetwork { + + // Configure retrofit to parse JSON and use coroutines + private val retrofit = Retrofit.Builder() + .baseUrl("https://android-kotlin-fun-mars-server.appspot.com/") + .addConverterFactory(MoshiConverterFactory.create()) + .build() + + val devbytes = retrofit.create(DevbyteService::class.java) + +} + + diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/repository/VideosRepository.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/repository/VideosRepository.kt new file mode 100755 index 000000000..d613ea57b --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/repository/VideosRepository.kt @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2019 Google Inc. + *gi + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.repository + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations +import com.example.android.devbyteviewer.database.VideosDatabase +import com.example.android.devbyteviewer.database.asDomainModel +import com.example.android.devbyteviewer.domain.DevByteVideo +import com.example.android.devbyteviewer.network.DevByteNetwork +import com.example.android.devbyteviewer.network.asDatabaseModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Repository for fetching devbyte videos from the network and storing them on disk + */ +class VideosRepository(private val database: VideosDatabase) { + + val videos: LiveData> = Transformations.map(database.videoDao.getVideos()) { + it.asDomainModel() + } + + suspend fun refreshVideos() { + withContext(Dispatchers.IO) { + val playlist = DevByteNetwork.devbytes.getPlaylist() + database.videoDao.insertAll(playlist.asDatabaseModel()) + } + } + +} + diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteActivity.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteActivity.kt new file mode 100755 index 000000000..b9a3647f8 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteActivity.kt @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.ui + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import com.example.android.devbyteviewer.R + +/** + * This is a single activity application that uses the Navigation library. Content is displayed + * by Fragments. + */ +class DevByteActivity : AppCompatActivity() { + + /** + * Called when the activity is starting. This is where most initialization + * should go + */ + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_dev_byte_viewer) + } +} diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteFragment.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteFragment.kt new file mode 100755 index 000000000..0ed6fed8b --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/ui/DevByteFragment.kt @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.ui + +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.annotation.LayoutRes +import androidx.databinding.DataBindingUtil +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProvider +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.example.android.devbyteviewer.R +import com.example.android.devbyteviewer.databinding.DevbyteItemBinding +import com.example.android.devbyteviewer.databinding.FragmentDevByteBinding +import com.example.android.devbyteviewer.domain.DevByteVideo +import com.example.android.devbyteviewer.viewmodels.DevByteViewModel + +/** + * Show a list of DevBytes on screen. + */ +class DevByteFragment : Fragment() { + + /** + * One way to delay creation of the viewModel until an appropriate lifecycle method is to use + * lazy. This requires that viewModel not be referenced before onActivityCreated, which we + * do in this Fragment. + */ + private val viewModel: DevByteViewModel by lazy { + val activity = requireNotNull(this.activity) { + "You can only access the viewModel after onActivityCreated()" + } + ViewModelProvider(this, DevByteViewModel.Factory(activity.application)) + .get(DevByteViewModel::class.java) + } + + /** + * RecyclerView Adapter for converting a list of Video to cards. + */ + private var viewModelAdapter: DevByteAdapter? = null + + /** + * Called immediately after onCreateView() has returned, and fragment's + * view hierarchy has been created. It can be used to do final + * initialization once these pieces are in place, such as retrieving + * views or restoring state. + */ + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + viewModel.playlist.observe(viewLifecycleOwner, Observer> { videos -> + videos?.apply { + viewModelAdapter?.videos = videos + } + }) + } + + /** + * Called to have the fragment instantiate its user interface view. + * + *

If you return a View from here, you will later be called in + * {@link #onDestroyView} when the view is being released. + * + * @param inflater The LayoutInflater object that can be used to inflate + * any views in the fragment, + * @param container If non-null, this is the parent view that the fragment's + * UI should be attached to. The fragment should not add the view itself, + * but this can be used to generate the LayoutParams of the view. + * @param savedInstanceState If non-null, this fragment is being re-constructed + * from a previous saved state as given here. + * + * @return Return the View for the fragment's UI. + */ + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + val binding: FragmentDevByteBinding = DataBindingUtil.inflate( + inflater, + R.layout.fragment_dev_byte, + container, + false) + // Set the lifecycleOwner so DataBinding can observe LiveData + binding.setLifecycleOwner(viewLifecycleOwner) + + binding.viewModel = viewModel + + viewModelAdapter = DevByteAdapter(VideoClick { + // When a video is clicked this block or lambda will be called by DevByteAdapter + + // context is not around, we can safely discard this click since the Fragment is no + // longer on the screen + val packageManager = context?.packageManager ?: return@VideoClick + + // Try to generate a direct intent to the YouTube app + var intent = Intent(Intent.ACTION_VIEW, it.launchUri) + if(intent.resolveActivity(packageManager) == null) { + // YouTube app isn't found, use the web url + intent = Intent(Intent.ACTION_VIEW, Uri.parse(it.url)) + } + + startActivity(intent) + }) + + binding.root.findViewById(R.id.recycler_view).apply { + layoutManager = LinearLayoutManager(context) + adapter = viewModelAdapter + } + + + // Observer for the network error. + viewModel.eventNetworkError.observe(viewLifecycleOwner, Observer { isNetworkError -> + if (isNetworkError) onNetworkError() + }) + + return binding.root + } + + /** + * Method for displaying a Toast error message for network errors. + */ + private fun onNetworkError() { + if(!viewModel.isNetworkErrorShown.value!!) { + Toast.makeText(activity, "Network Error", Toast.LENGTH_LONG).show() + viewModel.onNetworkErrorShown() + } + } + + /** + * Helper method to generate YouTube app links + */ + private val DevByteVideo.launchUri: Uri + get() { + val httpUri = Uri.parse(url) + return Uri.parse("vnd.youtube:" + httpUri.getQueryParameter("v")) + } +} + +/** + * Click listener for Videos. By giving the block a name it helps a reader understand what it does. + * + */ +class VideoClick(val block: (DevByteVideo) -> Unit) { + /** + * Called when a video is clicked + * + * @param video the video that was clicked + */ + fun onClick(video: DevByteVideo) = block(video) +} + +/** + * RecyclerView Adapter for setting up data binding on the items in the list. + */ +class DevByteAdapter(val callback: VideoClick) : RecyclerView.Adapter() { + + /** + * The videos that our Adapter will show + */ + var videos: List = emptyList() + set(value) { + field = value + // For an extra challenge, update this to use the paging library. + + // Notify any registered observers that the data set has changed. This will cause every + // element in our RecyclerView to be invalidated. + notifyDataSetChanged() + } + + /** + * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent + * an item. + */ + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DevByteViewHolder { + val withDataBinding: DevbyteItemBinding = DataBindingUtil.inflate( + LayoutInflater.from(parent.context), + DevByteViewHolder.LAYOUT, + parent, + false) + return DevByteViewHolder(withDataBinding) + } + + override fun getItemCount() = videos.size + + /** + * Called by RecyclerView to display the data at the specified position. This method should + * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given + * position. + */ + override fun onBindViewHolder(holder: DevByteViewHolder, position: Int) { + holder.viewDataBinding.also { + it.video = videos[position] + it.videoCallback = callback + } + } + +} + +/** + * ViewHolder for DevByte items. All work is done by data binding. + */ +class DevByteViewHolder(val viewDataBinding: DevbyteItemBinding) : + RecyclerView.ViewHolder(viewDataBinding.root) { + companion object { + @LayoutRes + val LAYOUT = R.layout.devbyte_item + } +} \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/BindingAdapters.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/BindingAdapters.kt new file mode 100755 index 000000000..e03a6d4f8 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/BindingAdapters.kt @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.util + +import android.view.View +import android.widget.ImageView +import androidx.databinding.BindingAdapter +import com.bumptech.glide.Glide + +/** + * Binding adapter used to hide the spinner once data is available. + */ +@BindingAdapter("isNetworkError", "playlist") +fun hideIfNetworkError(view: View, isNetWorkError: Boolean, playlist: Any?) { + view.visibility = if (playlist != null) View.GONE else View.VISIBLE + + if(isNetWorkError) { + view.visibility = View.GONE + } +} + +/** + * Binding adapter used to display images from URL using Glide + */ +@BindingAdapter("imageUrl") +fun setImageUrl(imageView: ImageView, url: String) { + Glide.with(imageView.context).load(url).into(imageView) +} \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/Util.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/Util.kt new file mode 100755 index 000000000..8da9996a9 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/util/Util.kt @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.util + +private val PUNCTUATION = listOf(", ", "; ", ": ", " ") + +/** + * Truncate long text with a preference for word boundaries and without trailing punctuation. + */ +fun String.smartTruncate(length: Int): String { + val words = split(" ") + var added = 0 + var hasMore = false + val builder = StringBuilder() + for (word in words) { + if (builder.length > length) { + hasMore = true + break + } + builder.append(word) + builder.append(" ") + added += 1 + } + + PUNCTUATION.map { + if (builder.endsWith(it)) { + builder.replace(builder.length - it.length, builder.length, "") + } + } + + if (hasMore) { + builder.append("...") + } + return builder.toString() +} \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/viewmodels/DevByteViewModel.kt b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/viewmodels/DevByteViewModel.kt new file mode 100755 index 000000000..1beb3fa88 --- /dev/null +++ b/RepositoryPattern/app/src/main/java/com/example/android/devbyteviewer/viewmodels/DevByteViewModel.kt @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.devbyteviewer.viewmodels + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import com.example.android.devbyteviewer.database.getDatabase +import com.example.android.devbyteviewer.domain.DevByteVideo +import com.example.android.devbyteviewer.network.DevByteNetwork +import com.example.android.devbyteviewer.network.asDomainModel +import com.example.android.devbyteviewer.repository.VideosRepository +import kotlinx.coroutines.* +import java.io.IOException + +/** + * DevByteViewModel designed to store and manage UI-related data in a lifecycle conscious way. This + * allows data to survive configuration changes such as screen rotations. In addition, background + * work such as fetching network results can continue through configuration changes and deliver + * results after the new Fragment or Activity is available. + * + * @param application The application that this viewmodel is attached to, it's safe to hold a + * reference to applications across rotation since Application is never recreated during actiivty + * or fragment lifecycle events. + */ +class DevByteViewModel(application: Application) : AndroidViewModel(application) { + + /** + * The data source this ViewModel will fetch results from. + */ + private val videosRepository = VideosRepository(getDatabase(application)) + + /** + * A playlist of videos displayed on the screen. + */ + val playlist = videosRepository.videos + /** + * A playlist of videos that can be shown on the screen. This is private to avoid exposing a + * way to set this value to observers. + */ + private val _playlist = MutableLiveData>() + + /** + * Event triggered for network error. This is private to avoid exposing a + * way to set this value to observers. + */ + private var _eventNetworkError = MutableLiveData(false) + + /** + * Event triggered for network error. Views should use this to get access + * to the data. + */ + val eventNetworkError: LiveData + get() = _eventNetworkError + + /** + * Flag to display the error message. This is private to avoid exposing a + * way to set this value to observers. + */ + private var _isNetworkErrorShown = MutableLiveData(false) + + /** + * Flag to display the error message. Views should use this to get access + * to the data. + */ + val isNetworkErrorShown: LiveData + get() = _isNetworkErrorShown + + /** + * init{} is called immediately when this ViewModel is created. + */ + init { + refreshDataFromRepository() + } + + /** + * Refresh data from the repository. Use a coroutine launch to run in a + * background thread. + */ + private fun refreshDataFromRepository() { + viewModelScope.launch { + try { + videosRepository.refreshVideos() + _eventNetworkError.value = false + _isNetworkErrorShown.value = false + + } catch (networkError: IOException) { + // Show a Toast error message and hide the progress bar. + if(playlist.value.isNullOrEmpty()) + _eventNetworkError.value = true + } + } + } + + + /** + * Resets the network error flag. + */ + fun onNetworkErrorShown() { + _isNetworkErrorShown.value = true + } + + /** + * Factory for constructing DevByteViewModel with parameter + */ + class Factory(val app: Application) : ViewModelProvider.Factory { + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(DevByteViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return DevByteViewModel(app) as T + } + throw IllegalArgumentException("Unable to construct viewmodel") + } + } +} diff --git a/RepositoryPattern/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/RepositoryPattern/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100755 index 000000000..56a256142 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + diff --git a/RepositoryPattern/app/src/main/res/drawable/ic_launcher_background.xml b/RepositoryPattern/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100755 index 000000000..4f6c04c0c --- /dev/null +++ b/RepositoryPattern/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/RepositoryPattern/app/src/main/res/drawable/ic_play_circle_outline_black_48dp.xml b/RepositoryPattern/app/src/main/res/drawable/ic_play_circle_outline_black_48dp.xml new file mode 100755 index 000000000..0d2e2855a --- /dev/null +++ b/RepositoryPattern/app/src/main/res/drawable/ic_play_circle_outline_black_48dp.xml @@ -0,0 +1,25 @@ + + + + + diff --git a/RepositoryPattern/app/src/main/res/layout/activity_dev_byte_viewer.xml b/RepositoryPattern/app/src/main/res/layout/activity_dev_byte_viewer.xml new file mode 100755 index 000000000..547d3628b --- /dev/null +++ b/RepositoryPattern/app/src/main/res/layout/activity_dev_byte_viewer.xml @@ -0,0 +1,33 @@ + + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/res/layout/devbyte_item.xml b/RepositoryPattern/app/src/main/res/layout/devbyte_item.xml new file mode 100755 index 000000000..926d2f4c5 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/layout/devbyte_item.xml @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/res/layout/fragment_dev_byte.xml b/RepositoryPattern/app/src/main/res/layout/fragment_dev_byte.xml new file mode 100755 index 000000000..235720679 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/layout/fragment_dev_byte.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + diff --git a/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100755 index 000000000..9b4f225c4 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100755 index 000000000..9b4f225c4 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher.png b/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100755 index 000000000..898f3ed59 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100755 index 000000000..dffca3601 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher.png b/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100755 index 000000000..64ba76f75 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100755 index 000000000..dae5e0823 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100755 index 000000000..e5ed46597 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100755 index 000000000..14ed0af35 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100755 index 000000000..b0907cac3 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100755 index 000000000..d8ae03154 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100755 index 000000000..2c18de9e6 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100755 index 000000000..beed3cdd2 Binary files /dev/null and b/RepositoryPattern/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/RepositoryPattern/app/src/main/res/navigation/nav_graph.xml b/RepositoryPattern/app/src/main/res/navigation/nav_graph.xml new file mode 100755 index 000000000..76fa28b5b --- /dev/null +++ b/RepositoryPattern/app/src/main/res/navigation/nav_graph.xml @@ -0,0 +1,29 @@ + + + + + + + \ No newline at end of file diff --git a/RepositoryPattern/app/src/main/res/values/colors.xml b/RepositoryPattern/app/src/main/res/values/colors.xml new file mode 100755 index 000000000..2a770efe7 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/values/colors.xml @@ -0,0 +1,26 @@ + + + + + #1E8E3E + #0D652D + #E37400 + + #ffDDDDDD + #ff666666 + #ff222222 + diff --git a/RepositoryPattern/app/src/main/res/values/strings.xml b/RepositoryPattern/app/src/main/res/values/strings.xml new file mode 100755 index 000000000..91f4c4d57 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/values/strings.xml @@ -0,0 +1,19 @@ + + + + DevByte Viewer + diff --git a/RepositoryPattern/app/src/main/res/values/styles.xml b/RepositoryPattern/app/src/main/res/values/styles.xml new file mode 100755 index 000000000..f668bf253 --- /dev/null +++ b/RepositoryPattern/app/src/main/res/values/styles.xml @@ -0,0 +1,27 @@ + + + + + + + + diff --git a/RepositoryPattern/build.gradle b/RepositoryPattern/build.gradle new file mode 100755 index 000000000..3626251f1 --- /dev/null +++ b/RepositoryPattern/build.gradle @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.6.10' + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:7.1.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.4.1" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/RepositoryPattern/gradle.properties b/RepositoryPattern/gradle.properties new file mode 100755 index 000000000..92cca3f16 --- /dev/null +++ b/RepositoryPattern/gradle.properties @@ -0,0 +1,31 @@ +# +# Copyright (C) 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +android.enableJetifier=true +android.useAndroidX=true +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/RepositoryPattern/gradle/wrapper/gradle-wrapper.jar b/RepositoryPattern/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 000000000..f6b961fd5 Binary files /dev/null and b/RepositoryPattern/gradle/wrapper/gradle-wrapper.jar differ diff --git a/RepositoryPattern/gradle/wrapper/gradle-wrapper.properties b/RepositoryPattern/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 000000000..c94a13c1d --- /dev/null +++ b/RepositoryPattern/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Aug 11 15:00:02 PDT 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip diff --git a/RepositoryPattern/gradlew b/RepositoryPattern/gradlew new file mode 100755 index 000000000..cccdd3d51 --- /dev/null +++ b/RepositoryPattern/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/RepositoryPattern/gradlew.bat b/RepositoryPattern/gradlew.bat new file mode 100755 index 000000000..e95643d6a --- /dev/null +++ b/RepositoryPattern/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/RepositoryPattern/settings.gradle b/RepositoryPattern/settings.gradle new file mode 100755 index 000000000..116b21c4e --- /dev/null +++ b/RepositoryPattern/settings.gradle @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +include ':app'