content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ayds.songinfo.home.model.repository.external.spotify.auth
import com.google.gson.Gson
import com.google.gson.JsonObject
interface SpotifyToTokenResolver {
fun getTokenFromExternalData(serviceData: String?): String?
}
private const val ACCESS_TOKEN = "access_token"
internal class JsonToTokenResolver : SpotifyToTokenResolver {
private val gson = Gson()
override fun getTokenFromExternalData(serviceData: String?): String {
val tokenResp = gson.fromJson(serviceData, JsonObject::class.java)
val accessToken = tokenResp[ACCESS_TOKEN]
return accessToken.asString
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/auth/SpotifyToTokenResolver.kt | 385779624 |
package ayds.songinfo.home.model.repository.external.spotify.auth
import android.util.Base64
import okhttp3.MediaType
import okhttp3.RequestBody
import retrofit2.Response
private const val clientId = "7db5d794e42845028ccabd50009e631f"
private const val clientSecret = "dc3db8626d86471b92662b72f5eff8ad"
interface SpotifyAccountService {
val token: String?
}
internal class SpotifyAccountServiceImpl(
private val spotifyTokenAPI: SpotifyAuthAPI,
private val resolver: SpotifyToTokenResolver
) : SpotifyAccountService {
override var token: String? = null
get() {
if (field == null) {
val tokenResponse = tokenFromService
field = getStringToken(tokenResponse)
}
return field
}
private set
private val tokenFromService: Response<String>
get() = spotifyTokenAPI.getToken(authorizationHeader, authorizationBody).execute()
private val authorizationBody: RequestBody = RequestBody.create(
MediaType.parse("application/x-www-form-urlencoded"), "grant_type=client_credentials"
)
private val authorizationHeader: String
get() {
val encodedData: String =
Base64.encodeToString("$clientId:$clientSecret".toByteArray(), Base64.NO_WRAP)
return "Basic $encodedData"
}
private fun getStringToken(tokenResponse: Response<String>): String? {
return resolver.getTokenFromExternalData(tokenResponse.body())
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/auth/SpotifyAccountService.kt | 619217379 |
package ayds.songinfo.home.model.repository.external.spotify.tracks
import ayds.songinfo.home.model.repository.external.spotify.SpotifyTrackService
import ayds.songinfo.home.model.repository.external.spotify.auth.SpotifyAuthInjector
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
object SpotifyTrackInjector {
private const val SPOTIFY_URL = "https://api.spotify.com/v1/"
private val spotifyAPIRetrofit = Retrofit.Builder()
.baseUrl(SPOTIFY_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
private val spotifyTrackAPI = spotifyAPIRetrofit.create(SpotifyTrackAPI::class.java)
private val spotifyToSongResolver: SpotifyToSongResolver = JsonToSongResolver()
val spotifyTrackService: SpotifyTrackService = SpotifyTrackServiceImpl(
spotifyTrackAPI,
SpotifyAuthInjector.spotifyAccountService,
spotifyToSongResolver
)
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/tracks/SpotifyTrackInjector.kt | 3921173114 |
package ayds.songinfo.home.model.repository.external.spotify.tracks
import com.google.gson.Gson
import ayds.songinfo.home.model.entities.Song.SpotifySong
import com.google.gson.JsonObject
interface SpotifyToSongResolver {
fun getSongFromExternalData(serviceData: String?): SpotifySong?
}
private const val TRACKS = "tracks"
private const val ITEMS = "items"
private const val ID = "id"
private const val NAME = "name"
private const val ARTISTS = "artists"
private const val ALBUM = "album"
private const val IMAGES = "images"
private const val RELEASE_DATE = "release_date"
private const val URL = "url"
private const val EXTERNAL_URL = "external_urls"
private const val SPOTIFY = "spotify"
private const val RELEASE_DATE_PRECISION = "release_date_precision"
internal class JsonToSongResolver : SpotifyToSongResolver {
override fun getSongFromExternalData(serviceData: String?): SpotifySong? =
try {
serviceData?.getFirstItem()?.let { item ->
SpotifySong(
item.getId(), item.getSongName(), item.getArtistName(), item.getAlbumName(),
item.getReleaseDate(), item.getSpotifyUrl(), item.getImageUrl(), item.getReleaseDatePrecision()
)
}
} catch (e: Exception) {
null
}
private fun String?.getFirstItem(): JsonObject {
val jobj = Gson().fromJson(this, JsonObject::class.java)
val tracks = jobj[TRACKS].asJsonObject
val items = tracks[ITEMS].asJsonArray
return items[0].asJsonObject
}
private fun JsonObject.getId() = this[ID].asString
private fun JsonObject.getSongName() = this[NAME].asString
private fun JsonObject.getArtistName(): String {
val artist = this[ARTISTS].asJsonArray[0].asJsonObject
return artist[NAME].asString
}
private fun JsonObject.getAlbumName(): String {
val album = this[ALBUM].asJsonObject
return album[NAME].asString
}
private fun JsonObject.getReleaseDate(): String {
val album = this[ALBUM].asJsonObject
return album[RELEASE_DATE].asString
}
private fun JsonObject.getImageUrl(): String {
val album = this[ALBUM].asJsonObject
return album[IMAGES].asJsonArray[1].asJsonObject[URL].asString
}
private fun JsonObject.getSpotifyUrl(): String {
val externalUrl = this[EXTERNAL_URL].asJsonObject
return externalUrl[SPOTIFY].asString
}
private fun JsonObject.getReleaseDatePrecision(): String {
val album = this[ALBUM].asJsonObject
return album[RELEASE_DATE_PRECISION].asString
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/tracks/SpotifyToSongResolver.kt | 707333354 |
package ayds.songinfo.home.model.repository.external.spotify.tracks
import ayds.songinfo.home.model.entities.Song.SpotifySong
import ayds.songinfo.home.model.repository.external.spotify.SpotifyTrackService
import ayds.songinfo.home.model.repository.external.spotify.auth.SpotifyAccountService
import retrofit2.Response
internal class SpotifyTrackServiceImpl(
private val spotifyTrackAPI: SpotifyTrackAPI,
private val spotifyAccountService: SpotifyAccountService,
private val spotifyToSongResolver: SpotifyToSongResolver,
) : SpotifyTrackService {
override fun getSong(title: String): SpotifySong? {
val callResponse = getSongFromService(title)
return spotifyToSongResolver.getSongFromExternalData(callResponse.body())
}
private fun getSongFromService(query: String): Response<String> {
return spotifyTrackAPI.getTrackInfo("Bearer " + spotifyAccountService.token, query)
.execute()
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/tracks/SpotifyTrackServiceImpl.kt | 72851412 |
package ayds.songinfo.home.model.repository.external.spotify.tracks
import retrofit2.Call
import retrofit2.http.*
internal interface SpotifyTrackAPI {
@GET("search?type=track")
fun getTrackInfo(
@Header("Authorization") token: String,
@Query("q") query: String
): Call<String>
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/repository/external/spotify/tracks/SpotifyTrackAPI.kt | 1094434458 |
package ayds.songinfo.home.model
import android.content.Context
import androidx.room.Room
import ayds.songinfo.home.model.repository.SongRepository
import ayds.songinfo.home.model.repository.SongRepositoryImpl
import ayds.songinfo.home.model.repository.external.spotify.SpotifyInjector
import ayds.songinfo.home.model.repository.external.spotify.SpotifyTrackService
import ayds.songinfo.home.model.repository.local.spotify.SpotifyLocalStorage
import ayds.songinfo.home.model.repository.local.spotify.room.SongDatabase
import ayds.songinfo.home.model.repository.local.spotify.room.SpotifyLocalStorageRoomImpl
import ayds.songinfo.home.view.HomeView
object HomeModelInjector {
private lateinit var homeModel: HomeModel
fun getHomeModel(): HomeModel = homeModel
fun initHomeModel(homeView: HomeView) {
val dataBase = Room.databaseBuilder(
homeView as Context,
SongDatabase::class.java, "song-database"
).build()
val spotifyLocalRoomStorage: SpotifyLocalStorage = SpotifyLocalStorageRoomImpl(dataBase)
val spotifyTrackService: SpotifyTrackService = SpotifyInjector.spotifyTrackService
val repository: SongRepository =
SongRepositoryImpl(spotifyLocalRoomStorage, spotifyTrackService)
homeModel = HomeModelImpl(repository)
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/HomeModelInjector.kt | 2662106822 |
package ayds.songinfo.home.model
import ayds.songinfo.home.model.entities.Song
import ayds.songinfo.home.model.repository.SongRepository
import ayds.observer.Observable
import ayds.observer.Subject
interface HomeModel {
val songObservable: Observable<Song>
fun searchSong(term: String)
fun getSongById(id: String): Song
}
internal class HomeModelImpl(private val repository: SongRepository) : HomeModel {
override val songObservable = Subject<Song>()
override fun searchSong(term: String) {
repository.getSongByTerm(term).let {
songObservable.notify(it)
}
}
override fun getSongById(id: String): Song = repository.getSongById(id)
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/HomeModel.kt | 4269496407 |
package ayds.songinfo.home.model.entities
sealed class Song {
data class SpotifySong(
val id: String,
val songName: String,
val artistName: String,
val albumName: String,
val releaseDate: String,
val spotifyUrl: String,
val imageUrl: String,
val releaseDatePrecision: String,
var isLocallyStored: Boolean = false
) : Song() {
//val year: String = releaseDate.split("-").first()
}
object EmptySong : Song()
}
| AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/model/entities/SpotifySong.kt | 240304655 |
package ayds.songinfo.home.view
data class HomeUiState(
val songId: String = "",
val searchTerm: String = "",
val songDescription: String = "",
val songImageUrl: String = DEFAULT_IMAGE,
val songUrl: String = "",
val actionsEnabled: Boolean = false,
) {
companion object {
const val DEFAULT_IMAGE = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Lisbon_%2836831596786%29_%28cropped%29.jpg/800px-Lisbon_%2836831596786%29_%28cropped%29.jpg"
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/HomeUiState.kt | 3181001692 |
package ayds.songinfo.home.view
import ayds.songinfo.home.model.entities.Song.EmptySong
import ayds.songinfo.home.model.entities.Song
import ayds.songinfo.home.model.entities.Song.SpotifySong
import ayds.songinfo.home.view.SongDateHelper
interface SongDescriptionHelper {
fun getSongDescriptionText(song: Song = EmptySong): String
}
internal class SongDescriptionHelperImpl(private val songDataHelperFactory: SongDataHelperFactory) : SongDescriptionHelper {
override fun getSongDescriptionText(song: Song): String {
return when (song) {
is SpotifySong ->
"${
"Song: ${song.songName} " +
if (song.isLocallyStored) "[*]" else ""
}\n" +
"Artist: ${song.artistName}\n" +
"Album: ${song.albumName}\n" +
"Release date: ${songDataHelperFactory.getSongDataHelper(song).getPrecisionDate()}"
else -> "Song not found"
}
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/SongDescriptionHelperImpl.kt | 3980715500 |
package ayds.songinfo.home.view
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import ayds.observer.Observable
import ayds.observer.Subject
import ayds.songinfo.R
import ayds.songinfo.home.model.HomeModel
import ayds.songinfo.home.model.HomeModelInjector
import ayds.songinfo.home.model.entities.Song
import ayds.songinfo.home.model.entities.Song.EmptySong
import ayds.songinfo.home.model.entities.Song.SpotifySong
import ayds.songinfo.home.view.HomeUiState.Companion.DEFAULT_IMAGE
import ayds.songinfo.utils.UtilsInjector
import ayds.songinfo.utils.navigation.NavigationUtils
import ayds.songinfo.utils.view.ImageLoader
interface HomeView {
val uiEventObservable: Observable<HomeUiEvent>
val uiState: HomeUiState
fun navigateToOtherDetails(artistName: String)
fun openExternalLink(url: String)
}
class HomeViewActivity : Activity(), HomeView {
private val onActionSubject = Subject<HomeUiEvent>()
private lateinit var homeModel: HomeModel
private val songDescriptionHelper: SongDescriptionHelper = HomeViewInjector.songDescriptionHelper
private val imageLoader: ImageLoader = UtilsInjector.imageLoader
private val navigationUtils: NavigationUtils = UtilsInjector.navigationUtils
private lateinit var searchButton: Button
private lateinit var modeDetailsButton: Button
private lateinit var openSongButton: Button
private lateinit var termEditText: EditText
private lateinit var descriptionTextView: TextView
private lateinit var posterImageView: ImageView
override val uiEventObservable: Observable<HomeUiEvent> = onActionSubject
override var uiState: HomeUiState = HomeUiState()
override fun navigateToOtherDetails(artistName: String) {
val intent = Intent(this, ayds.songinfo.moredetails.fulllogic.OtherInfoWindow::class.java)
intent.putExtra(ayds.songinfo.moredetails.fulllogic.OtherInfoWindow.ARTIST_NAME_EXTRA, artistName)
startActivity(intent)
}
override fun openExternalLink(url: String) {
navigationUtils.openExternalUrl(this, url)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initModule()
initProperties()
initListeners()
initObservers()
updateSongImage()
}
private fun initModule() {
HomeViewInjector.init(this)
homeModel = HomeModelInjector.getHomeModel()
}
private fun initProperties() {
searchButton = findViewById(R.id.searchButton)
modeDetailsButton = findViewById(R.id.modeDetailsButton)
openSongButton = findViewById(R.id.openSongButton)
termEditText = findViewById(R.id.termEditText)
descriptionTextView = findViewById(R.id.descriptionTextView)
posterImageView = findViewById(R.id.posterImageView)
}
private fun initListeners() {
searchButton.setOnClickListener {
hideKeyboard(termEditText)
searchAction()
}
modeDetailsButton.setOnClickListener { notifyMoreDetailsAction() }
openSongButton.setOnClickListener { notifyOpenSongAction() }
}
private fun searchAction() {
updateSearchTermState()
updateDisabledActionsState()
updateMoreDetailsState()
notifySearchAction()
}
private fun notifySearchAction() {
onActionSubject.notify(HomeUiEvent.Search)
}
private fun notifyMoreDetailsAction() {
onActionSubject.notify(HomeUiEvent.MoreDetails)
}
private fun notifyOpenSongAction() {
onActionSubject.notify(HomeUiEvent.OpenSongUrl)
}
private fun hideKeyboard(view: View) {
([email protected](INPUT_METHOD_SERVICE) as InputMethodManager).apply {
hideSoftInputFromWindow(view.windowToken, 0)
}
}
private fun updateSearchTermState() {
uiState = uiState.copy(searchTerm = termEditText.text.toString())
}
private fun updateDisabledActionsState() {
uiState = uiState.copy(actionsEnabled = false)
}
private fun initObservers() {
homeModel.songObservable
.subscribe { value -> updateSongInfo(value) }
}
private fun updateSongInfo(song: Song) {
updateUiState(song)
updateSongDescription()
updateSongImage()
updateMoreDetailsState()
}
private fun updateUiState(song: Song) {
when (song) {
is SpotifySong -> updateSongUiState(song)
EmptySong -> updateNoResultsUiState()
}
}
private fun updateSongUiState(song: SpotifySong) {
uiState = uiState.copy(
songId = song.id,
songImageUrl = song.imageUrl,
songUrl = song.spotifyUrl,
songDescription = songDescriptionHelper.getSongDescriptionText(song),
actionsEnabled = true
)
}
private fun updateNoResultsUiState() {
uiState = uiState.copy(
songId = "",
songImageUrl = DEFAULT_IMAGE,
songUrl = "",
songDescription = songDescriptionHelper.getSongDescriptionText(),
actionsEnabled = false
)
}
private fun updateSongDescription() {
runOnUiThread {
descriptionTextView.text = uiState.songDescription
}
}
private fun updateSongImage() {
runOnUiThread {
imageLoader.loadImageIntoView(uiState.songImageUrl, posterImageView)
}
}
private fun updateMoreDetailsState() {
enableActions(uiState.actionsEnabled)
}
private fun enableActions(enable: Boolean) {
runOnUiThread {
modeDetailsButton.isEnabled = enable
openSongButton.isEnabled = enable
}
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/HomeView.kt | 226533912 |
package ayds.songinfo.home.view
sealed class HomeUiEvent {
object Search : HomeUiEvent()
object MoreDetails : HomeUiEvent()
object OpenSongUrl : HomeUiEvent()
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/HomeUiEvent.kt | 2520257593 |
package ayds.songinfo.home.view
import ayds.songinfo.home.controller.HomeControllerInjector
import ayds.songinfo.home.model.HomeModelInjector
object HomeViewInjector {
val songDescriptionHelper: SongDescriptionHelper = SongDescriptionHelperImpl(SongDataHelperFactoryImpl())
fun init(homeView: HomeView) {
HomeModelInjector.initHomeModel(homeView)
HomeControllerInjector.onViewStarted(homeView)
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/HomeViewInjector.kt | 380583216 |
package ayds.songinfo.home.view
import ayds.songinfo.home.model.entities.Song
//----------Factory-------
//Se usaria en el INYECTOR para mantener dependencias y no se que factor SOLID
interface SongDataHelperFactory{
fun getSongDataHelper(song: Song.SpotifySong): SongDateHelper
}
class SongDataHelperFactoryImpl: SongDataHelperFactory{
override fun getSongDataHelper(song: Song.SpotifySong): SongDateHelper =
when (song.releaseDatePrecision) {
"day" -> SongDataDayHelper(song)
"month" -> SongDataMonthHelper(song)
else -> SongDataYearHelper(song)
}
}
//------------------------
interface SongDateHelper{
val song: Song.SpotifySong
fun getPrecisionDate(): String
}
internal class SongDataMonthHelper(override val song: Song.SpotifySong):SongDateHelper{
override fun getPrecisionDate(): String {
var toReturn: String = ""
val date = song.releaseDate
val monthAux = date.slice(listOf(5, 6))
when (monthAux) {
"01" -> toReturn += "January "
"02" -> toReturn += "February "
"03" -> toReturn += "March"
"04" -> toReturn += "April"
"05" -> toReturn += "May"
"06" -> toReturn += "June"
"07" -> toReturn += "July"
"08" -> toReturn += "August"
"09" -> toReturn += "September"
"10" -> toReturn += "October"
"11" -> toReturn += "November"
"12" -> toReturn += "December"
}
toReturn += ", " + date.slice(listOf(0, 1, 2, 3))
return toReturn
}
}
internal class SongDataDayHelper(override val song: Song.SpotifySong):SongDateHelper{
override fun getPrecisionDate(): String {
var toReturn: String = ""
val date = song.releaseDate
toReturn += date.slice(listOf(8, 9))
toReturn += "/" + date.slice(listOf(5, 6))
toReturn += "/" + date.slice(listOf(0, 1, 2, 3))
return toReturn
}
}
internal class SongDataYearHelper(override val song: Song.SpotifySong):SongDateHelper{
override fun getPrecisionDate(): String {
var toReturn: String = ""
val date = song.releaseDate
val yearAux = date.slice(listOf(0, 1, 2, 3))
toReturn += yearAux
if (yearAux.toInt() % 4 == 0)
toReturn += " (is a leap year)"
else
toReturn += " (not a leap year)"
return toReturn
}
}
| AyDS-SongInfo/app/src/main/java/ayds/songinfo/home/view/SongDateHelper.kt | 467625161 |
package ayds.songinfo.moredetails.fulllogic
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface LastFMAPI {
@GET("?method=artist.getinfo&api_key=0a657854db69e551c97d541ca9ebcef4&format=json")
fun getArtistInfo(@Query("artist") artist: String): Call<String>
}
| AyDS-SongInfo/app/src/main/java/ayds/songinfo/moredetails/fulllogic/LastFMAPI.kt | 3568565659 |
package ayds.songinfo.moredetails.fulllogic
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.room.Room.databaseBuilder
import ayds.songinfo.R
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.squareup.picasso.Picasso
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.IOException
import java.util.Locale
class OtherInfoWindow : Activity() {
private var textPane1: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_other_info)
textPane1 = findViewById(R.id.textPane1)
open(intent.getStringExtra("artistName"))
}
private fun getARtistInfo(artistName: String?) {
// create
val retrofit = Retrofit.Builder()
.baseUrl("https://ws.audioscrobbler.com/2.0/")
.addConverterFactory(ScalarsConverterFactory.create())
.build()
val lastFMAPI = retrofit.create(LastFMAPI::class.java)
Log.e("TAG", "artistName $artistName")
getARtistInfoFromDataBase(artistName, lastFMAPI)
}
private fun getARtistInfoFromDataBase(artistName: String?, lastFMAPI: LastFMAPI) {
Thread {
val article = dataBase!!.ArticleDao().getArticleByArtistName(artistName!!)
val text = if (article != null) { // exists in database
getInfoFromDataBase( article)
} else { // get from service
getInfoFromExternalService(lastFMAPI, artistName)
}
val imageUrl =
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Lastfm_logo.svg/320px-Lastfm_logo.svg.png"
Log.e("TAG", "Get Image from $imageUrl")
runOnUiThread {
Picasso.get().load(imageUrl).into(findViewById<View>(R.id.imageView1) as ImageView)
textPane1!!.text = Html.fromHtml(text)
}
}.start()
}
private fun getInfoFromExternalService(lastFMAPI: LastFMAPI, artistName: String): String {
var text1 = ""
val callResponse: Response<String>
try {
callResponse = lastFMAPI.getArtistInfo(artistName).execute()
Log.e("TAG", "JSON " + callResponse.body())
val gson = Gson()
val jobj = gson.fromJson(callResponse.body(), JsonObject::class.java)
val artist = jobj["artist"].getAsJsonObject()
val bio = artist["bio"].getAsJsonObject()
val extract = bio["content"]
val url = artist["url"]
text1 = if (extract == null) {
"No Results"
} else {
saveToDataBase(extract, artistName, url)
}
setURLOnClick(url)
} catch (e1: IOException) {
Log.e("TAG", "Error $e1")
e1.printStackTrace()
}
return text1
}
private fun setURLOnClick(url: JsonElement) {
findViewById<View>(R.id.openUrlButton1).setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse(url.asString))
startActivity(intent)
}
}
private fun saveToDataBase(extract: JsonElement, artistName: String, url: JsonElement): String {
val artistInfoModify = extract.asString.replace("\\n", "\n")
val artistInfoTOHTML = textToHtml(artistInfoModify, artistName)
// save to DB <o/
Thread {
dataBase!!.ArticleDao().insertArticle(
ArticleEntity(
artistName, artistInfoTOHTML, url.asString
)
)
}
.start()
return artistInfoTOHTML
}
private fun getInfoFromDataBase(article: ArticleEntity): String {
val text1 = "[*]" + article.biography
val urlString = article.articleUrl
findViewById<View>(R.id.openUrlButton1).setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse(urlString))
startActivity(intent)
}
return text1
}
private var dataBase: ArticleDatabase? = null
private fun open(artist: String?) {
dataBase =
databaseBuilder(this, ArticleDatabase::class.java, "database-name-thename").build()
Thread {
dataBase!!.ArticleDao().insertArticle(ArticleEntity("test", "sarasa", ""))
Log.e("TAG", "" + dataBase!!.ArticleDao().getArticleByArtistName("test"))
}.start()
getARtistInfo(artist)
}
companion object {
const val ARTIST_NAME_EXTRA = "artistName"
fun textToHtml(text: String, term: String?): String {
val builder = StringBuilder()
builder.append("<html><div width=400>")
builder.append("<font face=\"arial\">")
val textWithBold = text
.replace("'", " ")
.replace("\n", "<br>")
.replace(
"(?i)$term".toRegex(),
"<b>" + term!!.uppercase(Locale.getDefault()) + "</b>"
)
builder.append(textWithBold)
builder.append("</font></div></html>")
return builder.toString()
}
}
}
| AyDS-SongInfo/app/src/main/java/ayds/songinfo/moredetails/fulllogic/OtherInfoWindow.kt | 2926260512 |
package ayds.songinfo.moredetails.fulllogic
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.RoomDatabase
@Database(entities = [ArticleEntity::class], version = 1)
abstract class ArticleDatabase : RoomDatabase() {
abstract fun ArticleDao(): ArticleDao
}
@Entity
data class ArticleEntity(
@PrimaryKey
val artistName: String,
val biography: String,
val articleUrl: String,
)
@Dao
interface ArticleDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertArticle(article: ArticleEntity)
@Query("SELECT * FROM Articleentity WHERE artistName LIKE :artistName LIMIT 1")
fun getArticleByArtistName(artistName: String): ArticleEntity?
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/moredetails/fulllogic/Database.kt | 4227325990 |
package ayds.songinfo.utils
import ayds.songinfo.utils.navigation.NavigationUtils
import ayds.songinfo.utils.navigation.NavigationUtilsImpl
import ayds.songinfo.utils.view.ImageLoader
import ayds.songinfo.utils.view.ImageLoaderImpl
import com.squareup.picasso.Picasso
object UtilsInjector {
val imageLoader: ImageLoader = ImageLoaderImpl(Picasso.get())
val navigationUtils: NavigationUtils = NavigationUtilsImpl()
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/utils/UtilsInjector.kt | 1056780195 |
package ayds.songinfo.utils.navigation
import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
interface NavigationUtils {
fun openExternalUrl(activity: Activity, url: String)
}
internal class NavigationUtilsImpl: NavigationUtils {
override fun openExternalUrl(activity: Activity, url: String) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
activity.startActivity(intent)
}
}
| AyDS-SongInfo/app/src/main/java/ayds/songinfo/utils/navigation/NavigationUtils.kt | 631331130 |
package ayds.songinfo.utils.view
import android.widget.ImageView
import com.squareup.picasso.Picasso
interface ImageLoader {
fun loadImageIntoView(url: String, imageView: ImageView)
}
internal class ImageLoaderImpl(
private val picasso: Picasso
) : ImageLoader {
override fun loadImageIntoView(url: String, imageView: ImageView) {
picasso.load(url).into(imageView)
}
} | AyDS-SongInfo/app/src/main/java/ayds/songinfo/utils/view/ImageLoader.kt | 1907591824 |
package ayds.observer
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("ayds.observer.test", appContext.packageName)
}
} | AyDS-SongInfo/observer/src/androidTest/java/ayds/observer/ExampleInstrumentedTest.kt | 435907383 |
package ayds.observer
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | AyDS-SongInfo/observer/src/test/java/ayds/observer/ExampleUnitTest.kt | 1854919760 |
package ayds.observer
import java.util.*
class Subject<T> : Observable<T>, Publisher<T> {
private val observers: MutableList<Observer<T>> = ArrayList()
private var value: T? = null
override fun subscribe(observer: Observer<T>) {
observers.add(observer)
}
override fun unSubscribe(observer: Observer<T>) {
observers.remove(observer)
}
override fun notify(value: T) {
this.value = value
observers.forEach {
it.update(value)
}
}
fun lastValue(): T? {
return value
}
} | AyDS-SongInfo/observer/src/main/java/ayds/observer/Subject.kt | 146241804 |
package ayds.observer
interface Observable<T> {
fun subscribe(observer: Observer<T>)
fun unSubscribe(observer: Observer<T>)
}
fun interface Observer<T> {
fun update(value: T)
}
interface Publisher<T> {
fun notify(value: T)
} | AyDS-SongInfo/observer/src/main/java/ayds/observer/Observable.kt | 2738475705 |
package ayds.artist.external
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("ayds.artist.external.test", appContext.packageName)
}
} | AyDS-SongInfo/external/src/androidTest/java/ayds/artist/external/ExampleInstrumentedTest.kt | 2305993170 |
package ayds.artist.external
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | AyDS-SongInfo/external/src/test/java/ayds/artist/external/ExampleUnitTest.kt | 3210640823 |
package ayds.artist.external.wikipedia.data
data class WikipediaArticle(
var description: String,
var wikipediaURL: String,
var wikipediaLogoURL: String,
)
| AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/data/WikipediaArticle.kt | 1857571253 |
package ayds.artist.external.wikipedia.data
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface WikipediaTrackAPI {
@GET("api.php?action=query&list=search&utf8=&format=json&srlimit=1")
fun getArtistInfo(@Query("srsearch") artist: String): Call<String>
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/data/WikipediaTrackAPI.kt | 2973628539 |
package ayds.artist.external.wikipedia.data
interface WikipediaTrackService {
fun getInfo(artistName: String): WikipediaArticle?
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/data/WikipediaTrackService.kt | 2964404527 |
package ayds.artist.external.wikipedia.data
import com.google.gson.Gson
import com.google.gson.JsonObject
interface WikipediaToInfoResolver {
fun getInfoFromExternalData(serviceData: String?): WikipediaArticle?
}
private const val WIKIPEDIA_URL_PREFIX = "https://en.wikipedia.org/?curid="
private const val WIKIPEDIA_LOGO_URL = "https://upload.wikimedia.org/wikipedia/commons/8/8c/Wikipedia-logo-v2-es.png"
private const val SEARCH = "search"
private const val SNIPPET = "snippet"
private const val PAGE_ID = "pageid"
private const val QUERY = "query"
internal class JsonToInfoResolver : WikipediaToInfoResolver {
override fun getInfoFromExternalData(serviceData: String?): WikipediaArticle? =
try {
serviceData?.getFirstItem()?.let { item ->
WikipediaArticle(
item.getSnippet(),
item.getURL(),
wikipediaLogoURL = WIKIPEDIA_LOGO_URL
)
}
} catch (e: Exception) {
null
}
private fun String?.getFirstItem(): JsonObject {
val jsonObject = Gson().fromJson(this, JsonObject::class.java)
return jsonObject[QUERY].asJsonObject
}
private fun JsonObject.getSnippet() = this[SEARCH].asJsonArray[0].asJsonObject[SNIPPET].asString
private fun JsonObject.getURL() = "$WIKIPEDIA_URL_PREFIX${this.getPageID()}"
private fun JsonObject.getPageID() = this[SEARCH].asJsonArray[0].asJsonObject[PAGE_ID]
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/data/WikipediaToInfoResolver.kt | 3081464819 |
package ayds.artist.external.wikipedia.data
import retrofit2.Response
internal class WikipediaTrackServiceImpl(
private val wikipediaTrackAPI: WikipediaTrackAPI,
private val wikipediaToInfoResolver: WikipediaToInfoResolver,
) : WikipediaTrackService {
override fun getInfo(artistName: String): WikipediaArticle? {
val callResponse = getInfoFromService(artistName)
return wikipediaToInfoResolver.getInfoFromExternalData(callResponse.body())
}
private fun getInfoFromService(artistName: String): Response<String> {
return wikipediaTrackAPI.getArtistInfo(artistName)
.execute()
}
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/data/WikipediaTrackServiceImpl.kt | 982705826 |
package ayds.artist.external.wikipedia.injector
import ayds.artist.external.wikipedia.data.WikipediaTrackService
import ayds.artist.external.wikipedia.data.JsonToInfoResolver
import ayds.artist.external.wikipedia.data.WikipediaToInfoResolver
import ayds.artist.external.wikipedia.data.WikipediaTrackAPI
import ayds.artist.external.wikipedia.data.WikipediaTrackServiceImpl
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
private const val WIKIPEDIA_URL = "https://en.wikipedia.org/w/"
object WikipediaInjector {
private val wikipediaTrackAPI = getWikipediaAPI()
private val wikipediaToInfoResolver: WikipediaToInfoResolver = JsonToInfoResolver()
val wikipediaTrackService: WikipediaTrackService =
WikipediaTrackServiceImpl(
wikipediaTrackAPI,
wikipediaToInfoResolver
)
private fun getRetrofit() = Retrofit.Builder()
.baseUrl(WIKIPEDIA_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
private fun getWikipediaAPI() = getRetrofit().create(WikipediaTrackAPI::class.java)
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/wikipedia/injector/WikipediaInjector.kt | 1204501100 |
package ayds.artist.external.newyorktimes.data
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import retrofit2.Response
private const val PROP_RESPONSE = "response"
private const val WEB_URL = "web_url"
private const val DOCS = "docs"
interface NYTimesToArtistResolver {
fun getURL(response: Response<String>): String
fun generateFormattedResponse(response: Response<String>, nameArtist: String?): String?
}
class NYTimesToArtistResolverImpl : NYTimesToArtistResolver {
private fun getJson(callResponse: Response<String>): JsonObject {
val gson = Gson()
return gson.fromJson(callResponse.body(), JsonObject::class.java)
}
private fun getAsJsonObject(response: JsonObject): JsonElement? {
return response["docs"].asJsonArray[0].asJsonObject["abstract"]
}
private fun artistInfoAbstractToString(abstract: JsonElement, nameArtist: String?): String {
return abstract.asString.replace("\\n", "\n")
}
override fun getURL(response: Response<String>): String {
val jsonResponse = generateResponse(response)
return jsonResponse[DOCS].asJsonArray[0].asJsonObject[WEB_URL].asString
}
private fun generateResponse(response: Response<String>): JsonObject {
val jObj = getJson(response)
return jObj[PROP_RESPONSE].asJsonObject
}
override fun generateFormattedResponse(response: Response<String>, nameArtist: String?): String? {
val jsonResponse = generateResponse(response)
val abstract = getAsJsonObject(jsonResponse)
return if (abstract == null)
null
else
artistInfoAbstractToString(abstract, nameArtist)
}
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/data/NYTimesToArtistResolver.kt | 3858240097 |
package ayds.artist.external.newyorktimes.data
interface NYTimesService {
fun getArtistInfo(artistName: String?): NYTimesArticle
}
| AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/data/NYTimesService.kt | 3270604221 |
package ayds.artist.external.newyorktimes.data
const val NYT_LOGO_URL =
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRVioI832nuYIXqzySD8cOXRZEcdlAj3KfxA62UEC4FhrHVe0f7oZXp3_mSFG7nIcUKhg&usqp=CAU"
sealed class NYTimesArticle {
data class NYTimesArticleWithData(
val name: String?,
val info: String?,
val url: String,
): NYTimesArticle()
object EmptyArtistDataExternal : NYTimesArticle()
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/data/NYTimesArticle.kt | 2399956902 |
package ayds.artist.external.newyorktimes.data
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface NYTimesAPI {
@GET("articlesearch.json?api-key=fFnIAXXz8s8aJ4dB8CVOJl0Um2P96Zyx")
fun getArtistInfo(@Query("q") artist: String?): Call<String>
}
| AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/data/NYTimesAPI.kt | 2901923064 |
package ayds.artist.external.newyorktimes.data
import ayds.artist.external.newyorktimes.data.NYTimesArticle.EmptyArtistDataExternal
import ayds.artist.external.newyorktimes.data.NYTimesArticle.NYTimesArticleWithData
import java.io.IOException
internal class NYTimesServiceImpl(
private val nyTimesAPI: NYTimesAPI,
private val nyTimesToArtistResolver: NYTimesToArtistResolver,
) : NYTimesService {
override fun getArtistInfo(artistName: String?): NYTimesArticle {
var infoArtist: String? = null
try {
infoArtist = nyTimesToArtistResolver.generateFormattedResponse(getInfoFromAPI(artistName), artistName)
} catch (e1: IOException) {
e1.printStackTrace()
}
return if(infoArtist == null){
EmptyArtistDataExternal
}
else{
val response = getInfoFromAPI(artistName)
NYTimesArticleWithData(artistName, infoArtist, nyTimesToArtistResolver.getURL(response))
}
}
private fun getInfoFromAPI(artistName: String?) = nyTimesAPI.getArtistInfo(artistName).execute()
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/data/NYTimesServiceImpl.kt | 3434583827 |
package ayds.artist.external.newyorktimes.injector
import ayds.artist.external.newyorktimes.data.NYTimesAPI
import ayds.artist.external.newyorktimes.data.NYTimesService
import ayds.artist.external.newyorktimes.data.NYTimesServiceImpl
import ayds.artist.external.newyorktimes.data.NYTimesToArtistResolver
import ayds.artist.external.newyorktimes.data.NYTimesToArtistResolverImpl
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
private const val LINK_API_NYTIMES = "https://api.nytimes.com/svc/search/v2/"
object NYTimesInjector {
private val nyTimesAPI = getNYTimesAPI()
private val nyTimesToArtistResolver: NYTimesToArtistResolver = NYTimesToArtistResolverImpl()
val nyTimesService: NYTimesService = NYTimesServiceImpl(nyTimesAPI, nyTimesToArtistResolver)
private fun getNYTimesAPI(): NYTimesAPI {
val nyTimesAPIRetrofit = Retrofit.Builder()
.baseUrl(LINK_API_NYTIMES)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
return nyTimesAPIRetrofit.create(NYTimesAPI::class.java)
}
} | AyDS-SongInfo/external/src/main/java/ayds/artist/external/newyorktimes/injector/NYTimesInjector.kt | 198464785 |
interface Stack<T: Any>{
fun pop(): T?
fun push(element: T)
fun peek(): T?
val count : Int
val isEmpty: Boolean
get() = count == 0
}
class StackImpl<T: Any>:Stack<T>{
private val storage = arrayListOf<T>()
override val count: Int
get() = storage.size
override fun pop(): T? {
return storage.removeLastOrNull()
}
override fun peek(): T? {
return storage.lastOrNull()
}
override fun push(element: T) {
storage.add(element)
}
}
fun String.infixToPostfix(): String {
val stack = StackImpl<Char>()
val result = StringBuilder()
for (char in this) {
when {
char.isLetterOrDigit() -> result.append(char)
char == '(' -> stack.push(char)
char == ')' -> {
while (!stack.isEmpty && stack.peek() != '(') {
result.append(stack.pop())
}
stack.pop() // Pop the '('
}
else -> { // Operator
while (!stack.isEmpty && stack.peek()?.let { getPrecedence(it) }!! >= getPrecedence(char)) {
result.append(stack.pop())
}
stack.push(char)
}
}
}
while (!stack.isEmpty) {
result.append(stack.pop())
}
return result.toString()
}
fun getPrecedence(operator: Char): Int {
return when (operator) {
'+', '-' -> 1
'*', '/' -> 2
else -> 0
}
}
fun main() {
val infixExpression1 = "2 + 3 * 4"
val infixExpression2 = "(5 + 2) * 3 - 8 / 2"
val infixExpression3 = "a + b * (c - d) / e"
println(infixExpression1.infixToPostfix()) // Should print "234*+"
println(infixExpression2.infixToPostfix()) // Should print "52+3*82/-"
println(infixExpression3.infixToPostfix()) // Should print "abc-d*+e/"
}
| Stacks/src/Main.kt | 2447464989 |
package com.example.fragmenttransitionsample
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.fragmenttransitionsample", appContext.packageName)
}
} | FragmentTransitionSample/app/src/androidTest/java/com/example/fragmenttransitionsample/ExampleInstrumentedTest.kt | 3248295709 |
package com.example.fragmenttransitionsample
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | FragmentTransitionSample/app/src/test/java/com/example/fragmenttransitionsample/ExampleUnitTest.kt | 3810984671 |
package com.example.fragmenttransitionsample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.fragment.app.Fragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
changeFragment(AFragment.newInstance())
findViewById<Button>(R.id.btn_change_fragment).setOnClickListener {
changeFragment(BFragment.newInstance())
}
}
/**
* Fragment 전환 함수.
*/
private fun changeFragment(fragment: Fragment) {
supportFragmentManager
.beginTransaction()
.setCustomAnimations(
R.anim.slide_in,
R.anim.fade_out,
R.anim.fade_in,
R.anim.slide_out
)
.add(R.id.fl_fragment_wrapper, fragment) // replace() 메소드를 사용하면 결과가 다를까?
.addToBackStack(null)
.commit()
}
} | FragmentTransitionSample/app/src/main/java/com/example/fragmenttransitionsample/MainActivity.kt | 3227422950 |
package com.example.fragmenttransitionsample
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.transition.TransitionInflater
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [AFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class AFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false)
}
companion object {
@JvmStatic
fun newInstance() =
AFragment()
}
} | FragmentTransitionSample/app/src/main/java/com/example/fragmenttransitionsample/AFragment.kt | 1544503694 |
package com.example.fragmenttransitionsample
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.transition.TransitionInflater
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [BFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class BFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_b, container, false)
}
companion object {
@JvmStatic
fun newInstance() =
BFragment()
}
} | FragmentTransitionSample/app/src/main/java/com/example/fragmenttransitionsample/BFragment.kt | 713779974 |
package com.example.happybirthday
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.happybirthday", appContext.packageName)
}
} | LayoutBasicoAndroid/app/src/androidTest/java/com/example/happybirthday/ExampleInstrumentedTest.kt | 4291587392 |
package com.example.happybirthday
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | LayoutBasicoAndroid/app/src/test/java/com/example/happybirthday/ExampleUnitTest.kt | 2402542456 |
package com.example.happybirthday.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | LayoutBasicoAndroid/app/src/main/java/com/example/happybirthday/ui/theme/Color.kt | 10902474 |
package com.example.happybirthday.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun HappyBirthdayTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | LayoutBasicoAndroid/app/src/main/java/com/example/happybirthday/ui/theme/Theme.kt | 3850951464 |
package com.example.happybirthday.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | LayoutBasicoAndroid/app/src/main/java/com/example/happybirthday/ui/theme/Type.kt | 4120706125 |
package com.example.happybirthday
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.happybirthday.ui.theme.HappyBirthdayTheme
import androidx.compose.ui.unit.sp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HappyBirthdayTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GreetingText(message = "Happy Birthday Jobson!", from ="From Jobson")
}
}
}
}
}
@Composable
fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) {
Column(modifier = modifier) {
Text(
text = message,
fontSize = 100.sp,
lineHeight = 116.sp,
)
Text(
text = from,
fontSize = 36.sp
)
}
}
@Preview(showBackground = true)
@Composable
fun BirthdayCardPreview() {
HappyBirthdayTheme {
GreetingText(message = "Happy Birthday Jobson!", from ="From Jobson")
}
} | LayoutBasicoAndroid/app/src/main/java/com/example/happybirthday/MainActivity.kt | 1658837656 |
package com.travel.withaeng.config
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class TestConfiguration | withaeng-backend/withaeng-domain/src/test/kotlin/com/travel/withaeng/config/TestConfiguration.kt | 1559883541 |
package com.travel.withaeng.config
import com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.test.context.junit.jupiter.SpringExtension
@Disabled
@SpringBootTest
@ExtendWith(SpringExtension::class)
class JasyptConfigTest {
@Value("\${jasypt.encryptor.password}")
private lateinit var jasyptEncryptorPassword: String
@Autowired
private lateinit var configurableEnvironment: ConfigurableEnvironment
private lateinit var encryptor: DefaultLazyEncryptor
@BeforeEach
internal fun setUp() {
check(jasyptEncryptorPassword.isNotBlank()) {
"jasypt.encryptor.password must not be null, empty or blank. "
}
encryptor = DefaultLazyEncryptor(configurableEnvironment)
}
@Test
fun testForEncryption() {
val source = "test"
println("source: $source")
println("encrypted: ${encryptor.encrypt(source)}")
}
@Test
fun testForDecryption() {
val source = "test"
println("source: $source")
println("decrypted: ${encryptor.decrypt(source)}")
}
} | withaeng-backend/withaeng-domain/src/test/kotlin/com/travel/withaeng/config/JasyptConfigTest.kt | 4278269690 |
package com.travel.withaeng.converter
import com.travel.withaeng.domain.user.UserRole
import jakarta.persistence.AttributeConverter
class UserRoleConverter : AttributeConverter<Set<UserRole>, String> {
override fun convertToDatabaseColumn(attribute: Set<UserRole>): String {
return attribute.joinToString(DELIMITER) { it.name }
}
override fun convertToEntityAttribute(data: String): Set<UserRole> {
return data.split(DELIMITER).map { UserRole.valueOf(it.trim()) }.toSet()
}
companion object {
private const val DELIMITER = ","
}
} | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/converter/UserRoleConverter.kt | 2298283783 |
package com.travel.withaeng.config
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties
import org.springframework.context.annotation.Configuration
@EnableEncryptableProperties
@Configuration
class JasyptConfig | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/config/JasyptConfig.kt | 3890759217 |
package com.travel.withaeng.config
import com.travel.withaeng.domain.WithaengDomainModule
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@EnableJpaAuditing
@Configuration
@EntityScan(basePackageClasses = [WithaengDomainModule::class])
@EnableJpaRepositories(basePackageClasses = [WithaengDomainModule::class])
class JpaConfig | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/config/JpaConfig.kt | 1235931312 |
package com.travel.withaeng.domain.accompanyreply
import com.travel.withaeng.domain.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Table
@Table(name = "accompany_reply")
@Entity
class AccompanyReply(
@Column(name = "accompany_id", nullable = false)
val accompanyId: Long,
@Column(name = "user_id", nullable = false)
val userId: Long,
@Column(name = "content", nullable = false)
val content: String,
@Column(name = "depth", nullable = false)
val depth: Long,
@Column(name = "group_id", nullable = false)
val groupId: Long
) : BaseEntity() | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanyreply/AccompanyReply.kt | 4018712756 |
package com.travel.withaeng.domain.accompanyreply
import org.springframework.data.jpa.repository.JpaRepository
interface AccompanyReplyRepository : JpaRepository<AccompanyReply, Long> | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanyreply/AccompanyReplyRepository.kt | 2267698222 |
package com.travel.withaeng.domain.accompanyreply
data class AccompanyReplyDto(
val accompanyId: Long,
val userId: Long,
val content: String,
val depth: Long,
val groupId: Long
)
fun AccompanyReply.toDto(): AccompanyReplyDto = AccompanyReplyDto(
accompanyId = accompanyId,
userId = userId,
content = content,
depth = depth,
groupId = groupId
) | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanyreply/AccompanyReplyDto.kt | 554280353 |
package com.travel.withaeng.domain.user
import org.springframework.data.jpa.repository.JpaRepository
interface UserRepository : JpaRepository<User, Long> | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/user/UserRepository.kt | 2412553549 |
package com.travel.withaeng.domain.user
import java.time.LocalDate
data class UserDto(
val id: Long,
val email: String,
val password: String,
val nickname: String,
val birth: LocalDate? = null,
val isMale: Boolean? = null,
val profileImageUrl: String? = null,
val bio: String? = null,
val roles: Set<UserRole>
)
fun User.toDto(): UserDto = UserDto(
id = id,
email = email,
password = password,
nickname = nickname,
birth = birth,
isMale = isMale,
profileImageUrl = profileImageUrl,
bio = bio,
roles = roles
)
data class CreateUserDto(
val email: String,
val password: String,
val nickname: String,
val birth: LocalDate? = null,
val isMale: Boolean? = null,
val profileImageUrl: String? = null,
val bio: String? = null,
) | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/user/UserDto.kt | 1436681959 |
package com.travel.withaeng.domain.user
enum class UserRole(
val role: String
) {
USER("ROLE_USER"),
ADMIN("ROLE_ADMIN"),
} | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/user/UserRole.kt | 209019928 |
package com.travel.withaeng.domain.user
import com.travel.withaeng.converter.UserRoleConverter
import com.travel.withaeng.domain.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Convert
import jakarta.persistence.Entity
import jakarta.persistence.Table
import java.time.LocalDate
@Table(name = "users")
@Entity
class User(
@Column(name = "email", nullable = false)
val email: String,
@Column(name = "password", nullable = false)
val password: String,
@Column(name = "nickname", nullable = false)
val nickname: String,
@Column(name = "birth", nullable = true)
val birth: LocalDate? = null,
@Column(name = "is_male", nullable = true)
val isMale: Boolean? = null,
@Column(name = "profile_image_url")
val profileImageUrl: String? = null,
@Column(name = "bio")
val bio: String? = null,
@Convert(converter = UserRoleConverter::class)
@Column(name = "roles")
val roles: Set<UserRole>,
) : BaseEntity() {
companion object {
fun create(
email: String,
password: String,
nickname: String,
birth: LocalDate? = null,
isMale: Boolean? = null,
profileImageUrl: String? = null,
bio: String? = null,
): User {
return User(
email = email,
password = password,
nickname = nickname,
profileImageUrl = profileImageUrl,
birth = birth,
isMale = isMale,
bio = bio,
roles = setOf(UserRole.USER)
)
}
}
} | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/user/User.kt | 3831791252 |
package com.travel.withaeng.domain.user
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional(readOnly = true)
class UserService(private val userRepository: UserRepository) {
@Transactional
fun createUser(createUserDto: CreateUserDto): UserDto {
return userRepository.save(
User.create(
email = createUserDto.email,
password = createUserDto.password,
nickname = createUserDto.nickname,
profileImageUrl = createUserDto.profileImageUrl,
birth = createUserDto.birth,
isMale = createUserDto.isMale,
bio = createUserDto.bio
)
).toDto()
}
} | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/user/UserService.kt | 1674625284 |
package com.travel.withaeng.domain
interface WithaengDomainModule | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/WithaengDomainModule.kt | 1207132679 |
package com.travel.withaeng.domain
import jakarta.persistence.*
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
@EntityListeners(AuditingEntityListener::class)
@MappedSuperclass
abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
val id: Long = 0L
@CreatedDate
@Column(name = "created_at", nullable = false, updatable = false)
var createdAt: LocalDateTime = LocalDateTime.now()
@LastModifiedDate
@Column(name = "updated_at", nullable = false, updatable = true)
var updatedAt: LocalDateTime = LocalDateTime.now()
@Column(name = "deleted_at", nullable = true, updatable = true)
var deletedAt: LocalDateTime? = null
} | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/BaseEntity.kt | 1028455564 |
package com.travel.withaeng.domain.accompanyreplylike
import com.travel.withaeng.domain.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Table
@Table(name = "accompany_reply_like")
@Entity
class AccompanyReplyLike(
@Column(name = "accompany_reply_id", nullable = false)
val accompanyReplyId: Long,
@Column(name = "user_id", nullable = false)
val userId: Long
) : BaseEntity() | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanyreplylike/AccompanyReplyLike.kt | 2664370984 |
package com.travel.withaeng.domain.accompanyreplylike
import org.springframework.data.jpa.repository.JpaRepository
interface AccompanyReplyLikeRepository : JpaRepository<AccompanyReplyLike, Long> | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanyreplylike/AccompanyReplyLikeRepository.kt | 2179590587 |
package com.travel.withaeng.domain.accompanylike
import com.travel.withaeng.domain.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Table
@Table(name = "accompany_like")
@Entity
class AccompanyLike(
@Column(name = "user_id", nullable = false)
val userId: Long,
@Column(name = "accompany_id", nullable = false)
val accompanyId: Long
) : BaseEntity() | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanylike/AccompanyLike.kt | 555702932 |
package com.travel.withaeng.domain.accompanylike
import org.springframework.data.jpa.repository.JpaRepository
interface AccompanyLikeRepository : JpaRepository<AccompanyLike, Long> | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompanylike/AccompanyLikeRepository.kt | 1981665363 |
package com.travel.withaeng.domain.accompany
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
@Embeddable
data class Destination(
@Column(name = "continent", nullable = false)
val continent: String,
@Column(name = "country", nullable = false)
val country: String,
@Column(name = "city", nullable = false)
val city: String
) | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompany/Destination.kt | 3529621719 |
package com.travel.withaeng.domain.accompany
import com.travel.withaeng.domain.BaseEntity
import jakarta.persistence.*
import java.time.LocalDate
@Table(name = "accompany")
@Entity
class Accompany(
@Column(name = "user_id", nullable = false)
val userId: Long,
@Column(name = "title", nullable = false)
val title: String,
@Lob
@Column(name = "content", nullable = false)
val content: String,
@Embedded
val destination: Destination,
@Column(name = "start_trip_date", nullable = false)
val startTripDate: LocalDate,
@Column(name = "end_trip_date", nullable = false)
val endTripDate: LocalDate,
@Column(name = "banner_image_url")
val bannerImageUrl: String?,
@Column(name = "view_counts", nullable = false)
val viewCounts: Long = 0L
) : BaseEntity() | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompany/Accompany.kt | 1650899654 |
package com.travel.withaeng.domain.accompany
import java.time.LocalDate
import java.time.LocalDateTime
data class AccompanyDto(
val userId: Long,
val title: String,
val content: String,
val destination: Destination,
val startTripDate: LocalDate,
val endTripDate: LocalDate,
val bannerImageUrl: String?,
val viewCounts: Long,
val createdAt: LocalDateTime
)
fun Accompany.toDto(): AccompanyDto = AccompanyDto(
userId = userId,
title = title,
content = content,
destination = destination,
startTripDate = startTripDate,
endTripDate = endTripDate,
bannerImageUrl = bannerImageUrl,
viewCounts = viewCounts,
createdAt = createdAt
) | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompany/AccompanyDto.kt | 4037863337 |
package com.travel.withaeng.domain.accompany
import org.springframework.data.jpa.repository.JpaRepository
interface AccompanyRepository : JpaRepository<Accompany, Long> | withaeng-backend/withaeng-domain/src/main/kotlin/com/travel/withaeng/domain/accompany/AccompanyRepository.kt | 3606426771 |
package com.travel.withaeng.common.exception
enum class WithaengExceptionType(
val message: String,
val errorCode: String,
val httpStatusCode: Int,
) {
// USER
AUTH_ERROR("유저 프로세스에서 오류가 발생했습니다.", "U000_AUTH_ERROR", 500),
EMPTY_AUTHORIZATION_HEADER("Not Exist Authorization Header", "U001_EMPTY_AUTHORIZATION_HEADER", 400),
INVALID_USER_AUTH_TOKEN("Invalid JWT Token", "U002_INVALID_TOKEN", 400),
INVALID_AUTH_PROVIDER(
"Invalid provider by auth0. Check social section of auth0",
"U003_INVALID_AUTH_PROVIDER",
500
),
EMPTY_FCM_TOKEN("Not Exist FCM Token", "U004_EMPTY_FCM_TOKEN", 400),
// COMMON
NOT_EXIST("존재하지 않습니다.", "C001_NOT_EXIST", 404),
SYSTEM_FAIL("Internal Server Error.", "C002_SYSTEM_FAIL", 500),
INVALID_ACCESS("Invalid Access", "C003_INVALID_ACCESS", 403),
ALREADY_EXIST("Already Exist", "C004_ALREADY_EXIST", 409),
INVALID_INPUT("Invalid Input", "C004_INVALID_INPUT", 400),
METHOD_ARGUMENT_TYPE_MISMATCH_VALUE("Request method argument type mismatch", "C005_TYPE_MISMATCH_VALUE", 400),
HTTP_REQUEST_METHOD_NOT_SUPPORTED("HTTP request method not supported", "C006_HTTP_METHOD_NOT_SUPPORTED", 400),
ACCESS_DENIED("Access denied. Check authentication.", "C007_ACCESS_DENIED", 403),
AUTHENTICATION_FAILURE("Authentication failed. Check login.", "C008_AUTHENTICATION_FAILURE", 401),
ARGUMENT_NOT_VALID("Method Argument Not Valid. Check argument validation.", "C009_ARGUMENT_NOT_VALID", 400),
// NOTIFICATION
INVALID_NOTIFICATION_TYPE("Invalid Notification Type", "N001_INVALID_NOTIFICATION_TYPE", 500),
;
}
| withaeng-backend/withaeng-common/src/main/kotlin/com/travel/withaeng/common/exception/WithaengExceptionType.kt | 3021022396 |
package com.travel.withaeng.common.exception
class WithaengException(
val errorCode: String,
val httpStatusCode: Int,
override val message: String,
) : RuntimeException() {
companion object {
fun of(type: WithaengExceptionType): WithaengException {
return WithaengException(
errorCode = type.errorCode,
httpStatusCode = type.httpStatusCode,
message = type.message,
)
}
fun of(type: WithaengExceptionType, message: String): WithaengException {
return WithaengException(
errorCode = type.errorCode,
httpStatusCode = type.httpStatusCode,
message = message,
)
}
}
}
| withaeng-backend/withaeng-common/src/main/kotlin/com/travel/withaeng/common/exception/WithaengException.kt | 2587153945 |
package com.travel.withaeng.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.travel.withaeng.security.jwt.JwtAgent
import com.travel.withaeng.security.jwt.JwtAgentImpl
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(AuthProperty::class)
class AuthConfig {
@Bean
fun jwtAgent(mapper: ObjectMapper, authProperty: AuthProperty): JwtAgent {
return JwtAgentImpl(mapper, authProperty.jwtSecretKey, authProperty.jwtIssuer)
}
}
@ConfigurationProperties(prefix = "witheang.auth")
data class AuthProperty(val jwtSecretKey: String, val jwtIssuer: String)
| withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/config/AuthConfig.kt | 2095010852 |
package com.travel.withaeng.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.travel.withaeng.security.handler.HttpStatusAccessDeniedHandler
import com.travel.withaeng.security.handler.HttpStatusAuthenticationEntryPoint
import com.travel.withaeng.security.jwt.JwtAgent
import com.travel.withaeng.security.jwt.JwtFilter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpHeaders
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
@Configuration
@EnableWebSecurity
class SecurityConfig(private val jwtAgent: JwtAgent, private val objectMapper: ObjectMapper) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
return http
.cors { it.configurationSource(corsConfigurationSource()) }
.csrf { it.disable() }
.httpBasic { it.disable() }
.formLogin { it.disable() }
.authorizeHttpRequests {
it.anyRequest().permitAll() // TODO: 추후 인가 추가
}
.addFilterBefore(JwtFilter(jwtAgent, objectMapper), UsernamePasswordAuthenticationFilter::class.java)
.exceptionHandling {
it.authenticationEntryPoint(HttpStatusAuthenticationEntryPoint())
it.accessDeniedHandler(HttpStatusAccessDeniedHandler())
}
.build()
}
@Bean
fun webSecurityCustomizer(): WebSecurityCustomizer {
return WebSecurityCustomizer {
it.ignoring().requestMatchers(*WHITE_LIST.toTypedArray())
}
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration().apply {
addAllowedOriginPattern("*")
addAllowedMethod("*")
addAllowedHeader("*")
exposedHeaders = listOf(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE)
maxAge = MAX_CORS_EXPIRE_SECONDS
}
return UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/v1/**", configuration)
}
}
companion object {
private const val MAX_CORS_EXPIRE_SECONDS = 3600L
private val WHITE_LIST = listOf(
// swagger
"/api-docs/**", "/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**",
// error page
"/error/**",
// Auth endpoints
"/v1/auth/**",
)
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/config/SecurityConfig.kt | 1148756861 |
package com.travel.withaeng.security.jwt
import com.fasterxml.jackson.databind.ObjectMapper
import com.travel.withaeng.common.exception.WithaengException
import com.travel.withaeng.common.exception.WithaengExceptionType
import com.travel.withaeng.security.authentication.UserInfo
import io.jsonwebtoken.JwtParser
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import org.springframework.beans.factory.annotation.Value
import java.security.Key
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.*
class JwtAgentImpl(
private val objectMapper: ObjectMapper,
@Value("\${jwt.issuer}") private val issuer: String,
@Value("\${jwt.secret-key}") key: String,
) : JwtAgent {
private val secretKey: Key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(key))
private val jwtParser: JwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build()
override fun provide(userInfo: UserInfo): String {
val issuerDateTime = LocalDateTime.now(ASIA_SEOUL_ZONE_ID)
val expiredDateTime = issuerDateTime.plusDays(TOKEN_EXPIRE_DAY)
return Jwts.builder()
.setHeaderParam(KEY_TOKEN_TYPE, TOKEN_TYPE_JWT)
.setSubject(createSubject(userInfo.nickname))
.setAudience("${userInfo.email}|${userInfo.id}|${userInfo.nickname}")
.setIssuer(issuer)
.setIssuedAt(issuerDateTime.convertToDate())
.setExpiration(expiredDateTime.convertToDate())
.claim(KEY_CLAIM_INFO, userInfo)
.signWith(secretKey)
.compact()
}
override fun extractUserInfoFromToken(token: String): UserInfo {
return jwtParser.parseClaimsJws(token).body?.let { claims ->
objectMapper.convertValue(claims[KEY_CLAIM_INFO], UserInfo::class.java)
} ?: throw WithaengException.of(WithaengExceptionType.INVALID_USER_AUTH_TOKEN)
}
private fun LocalDateTime.convertToDate(): Date = Date.from(this.toInstant(ASIA_SEOUL_ZONE_OFFSET))
private fun createSubject(subject: String): String = "jwt-user-$subject"
companion object {
private const val KEY_CLAIM_INFO = "info"
private const val KEY_TOKEN_TYPE = "typ"
private const val TOKEN_TYPE_JWT = "JWT"
private val ASIA_SEOUL_ZONE_ID = ZoneId.of("Asia/Seoul")
private val ASIA_SEOUL_ZONE_OFFSET = ZoneOffset.of("+09:00")
private const val TOKEN_EXPIRE_DAY = 7L // 임시 JWT 만료기간
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/jwt/JwtAgentImpl.kt | 138318775 |
package com.travel.withaeng.security.jwt
import com.fasterxml.jackson.databind.ObjectMapper
import com.travel.withaeng.common.ApiResponse
import com.travel.withaeng.common.Constants.Authentication.BEARER_TYPE
import com.travel.withaeng.common.exception.WithaengException
import com.travel.withaeng.common.exception.WithaengExceptionType
import com.travel.withaeng.security.authentication.JwtAuthentication
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.OncePerRequestFilter
class JwtFilter(
private val jwtAgent: JwtAgent,
private val objectMapper: ObjectMapper
) : OncePerRequestFilter() {
private val log: Logger = LoggerFactory.getLogger(JwtFilter::class.java)
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
log.debug("JWT Filter doFilterInternal()")
runCatching {
setAuthenticationFromToken(request)
}.onFailure { exception ->
log.debug("Authentication Failed: Authorization value=${request.getAuthorization()}, Message=${exception.message}")
SecurityContextHolder.clearContext()
response.run {
status = HttpStatus.UNAUTHORIZED.value()
addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
val failResponse = ApiResponse.fail(WithaengExceptionType.AUTHENTICATION_FAILURE, exception.message)
writer.write(objectMapper.writeValueAsString(failResponse))
}
}.onSuccess {
filterChain.doFilter(request, response)
}
}
private fun setAuthenticationFromToken(request: HttpServletRequest) {
if (!isNotCheckEndpoint(request)) {
val authorization =
request.getAuthorization()
?: throw BadCredentialsException(WithaengExceptionType.AUTHENTICATION_FAILURE.message)
log.debug("Parsing token in header: $authorization - Request path: ${request.requestURI}")
getToken(authorization)?.let { token ->
jwtAgent.extractUserInfoFromToken(token)?.let { userInfo ->
SecurityContextHolder.getContext().authentication = JwtAuthentication(userInfo)
}
} ?: throw WithaengException.of(WithaengExceptionType.AUTHENTICATION_FAILURE)
}
}
private fun getToken(authorization: String): String? {
val (provider, token) = authorization.split(AUTH_PROVIDER_SPLIT_DELIMITER)
if (provider.uppercase() != BEARER_TYPE.uppercase()) return null
return token
}
private fun HttpServletRequest.getAuthorization(): String? = getHeader(HttpHeaders.AUTHORIZATION)
private fun isNotCheckEndpoint(request: HttpServletRequest): Boolean {
return NOT_CHECK_ENDPOINTS.any { request.requestURI.startsWith(it) }
}
companion object {
private const val AUTH_PROVIDER_SPLIT_DELIMITER: String = " "
private val NOT_CHECK_ENDPOINTS = listOf(
// Common
"/favicon.ico",
"/error",
// Swagger
"/api-docs", "/swagger-ui", "/swagger-resources",
// SignIn/SignUp Endpoints
"/v1/auth",
)
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/jwt/JwtFilter.kt | 1732149649 |
package com.travel.withaeng.security.jwt
import com.travel.withaeng.security.authentication.UserInfo
interface JwtAgent {
/**
* 사용자 정보를 토대로 Jwt Token을 생성합니다.
* JwtToken은 accessToken및 refreshToken을 포함합니다.
*
* @param userInfo UserInfo 로 유저의 정보를 담고 있습니다.
* @return JWT 를 반환합니다.
*/
fun provide(userInfo: UserInfo): String
/**
* 사용자의 accessToken을 입력받아 UserInfo 객체를 반환합니다.
*
* @param token 사용자가 발급받은 JWT
* @return UserInfo 를 반환합니다.
*/
fun extractUserInfoFromToken(token: String): UserInfo?
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/jwt/JwtAgent.kt | 2396999603 |
package com.travel.withaeng.security.handler
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.AuthenticationEntryPoint
class HttpStatusAuthenticationEntryPoint : AuthenticationEntryPoint {
private val log: Logger = LoggerFactory.getLogger(HttpStatusAuthenticationEntryPoint::class.java)
override fun commence(
request: HttpServletRequest, response: HttpServletResponse,
authException: AuthenticationException
) {
log.debug("Not Authenticated: ${authException.message}")
response.status = HttpStatus.UNAUTHORIZED.value()
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/handler/HttpStatusAuthenticationEntryPoint.kt | 2284401214 |
package com.travel.withaeng.security.handler
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.security.web.access.AccessDeniedHandler
class HttpStatusAccessDeniedHandler : AccessDeniedHandler {
private val log: Logger = LoggerFactory.getLogger(HttpStatusAccessDeniedHandler::class.java)
override fun handle(
request: HttpServletRequest?,
response: HttpServletResponse,
accessDeniedException: org.springframework.security.access.AccessDeniedException
) {
log.debug("Access Denied: ${accessDeniedException.message}")
response.status = HttpStatus.FORBIDDEN.value()
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/handler/HttpStatusAccessDeniedHandler.kt | 132752732 |
package com.travel.withaeng.security.authentication
import com.travel.withaeng.domain.user.UserDto
import com.travel.withaeng.domain.user.UserRole
data class UserInfo(
val id: Long,
val email: String,
val nickname: String,
val roles: Set<UserRole>,
) {
companion object {
fun from(user: UserDto): UserInfo {
return UserInfo(
id = user.id,
email = user.email,
nickname = user.nickname,
roles = user.roles
)
}
}
}
| withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/authentication/UserInfo.kt | 2065984107 |
package com.travel.withaeng.security.authentication
import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
class JwtAuthentication(private val userInfo: UserInfo) : Authentication {
var isAuthenticated = true
override fun getName(): String = userInfo.nickname
override fun getAuthorities(): Collection<GrantedAuthority> = userInfo.roles
.map { userRole -> SimpleGrantedAuthority(userRole.role) }
override fun getCredentials(): Any = userInfo.id
override fun getDetails(): Any = userInfo.toDetails()
override fun getPrincipal(): Any = userInfo
override fun isAuthenticated(): Boolean = isAuthenticated
override fun setAuthenticated(isAuthenticated: Boolean) {
this.isAuthenticated = isAuthenticated
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/security/authentication/JwtAuthentication.kt | 1957230220 |
package com.travel.withaeng
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class WithaengApplication
fun main(args: Array<String>) {
runApplication<WithaengApplication>(*args)
}
| withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/WithaengApplication.kt | 407069916 |
package com.travel.withaeng.common
import com.travel.withaeng.common.exception.WithaengException
import com.travel.withaeng.common.exception.WithaengExceptionType
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.BindException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
@RestControllerAdvice
class ControllerExceptionAdvice {
private val logger: Logger = LoggerFactory.getLogger(ControllerExceptionAdvice::class.java)
@ExceptionHandler(Exception::class)
fun handleException(ex: Exception): ResponseEntity<ApiResponse<Any>> {
logger.error("Exception handler", ex)
return errorResponse(WithaengExceptionType.SYSTEM_FAIL, ex.message)
}
@ExceptionHandler(WithaengException::class)
fun handleMoitException(ex: WithaengException): ResponseEntity<ApiResponse<Any>> {
logger.error("WitheangException handler", ex)
return errorResponse(ex.httpStatusCode, ex.toApiErrorResponse())
}
@ExceptionHandler(MissingServletRequestParameterException::class)
protected fun handleMissingServletRequestParameterException(ex: MissingServletRequestParameterException): ResponseEntity<ApiResponse<Any>> {
logger.error("MissingServletRequestParameterException handler", ex)
return errorResponse(WithaengExceptionType.INVALID_INPUT, ex.message)
}
@ExceptionHandler(BindException::class)
protected fun handleBindException(ex: BindException): ResponseEntity<ApiResponse<Any>> {
logger.error("BindException handler", ex)
return errorResponse(WithaengExceptionType.INVALID_INPUT, ex.message)
}
@ExceptionHandler(MethodArgumentTypeMismatchException::class)
protected fun handleMethodArgumentTypeMismatchException(ex: MethodArgumentTypeMismatchException): ResponseEntity<ApiResponse<Any>> {
logger.error("MethodArgumentTypeMismatchException handler", ex)
return errorResponse(WithaengExceptionType.METHOD_ARGUMENT_TYPE_MISMATCH_VALUE, ex.message)
}
@ExceptionHandler(HttpRequestMethodNotSupportedException::class)
protected fun handleHttpRequestMethodNotSupportedException(ex: HttpRequestMethodNotSupportedException): ResponseEntity<ApiResponse<Any>> {
logger.error("HttpRequestMethodNotSupportedException handler", ex)
return errorResponse(WithaengExceptionType.HTTP_REQUEST_METHOD_NOT_SUPPORTED, ex.message)
}
@ExceptionHandler(AccessDeniedException::class)
protected fun handleAccessDeniedException(ex: AccessDeniedException): ResponseEntity<ApiResponse<Any>> {
logger.error("AccessDeniedException handler", ex)
return errorResponse(WithaengExceptionType.ACCESS_DENIED, ex.message)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
protected fun handleMethodArgumentNotValidException(e: MethodArgumentNotValidException): ResponseEntity<ApiResponse<Any>> {
logger.error("MethodArgumentNotValidException handler", e)
val errorMessage = e.allErrors.joinToString(" ,")
return errorResponse(WithaengExceptionType.ARGUMENT_NOT_VALID, errorMessage)
}
private fun WithaengException.toApiErrorResponse() = ApiErrorResponse(
code = errorCode,
message = message,
)
private fun errorResponse(
exceptionType: WithaengExceptionType,
message: String?
) = errorResponse(
exceptionType.httpStatusCode,
ApiErrorResponse(exceptionType.name, message)
)
private fun errorResponse(status: Int, errorResponse: ApiErrorResponse) =
errorResponse(HttpStatus.valueOf(status), errorResponse)
private fun errorResponse(status: HttpStatus, errorResponse: ApiErrorResponse): ResponseEntity<ApiResponse<Any>> =
ResponseEntity.status(status)
.body(
ApiResponse(
success = false,
data = null,
error = errorResponse,
)
)
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/common/ControllerExceptionAdvice.kt | 1082660072 |
package com.travel.withaeng.common
import com.travel.withaeng.common.exception.WithaengExceptionType
data class ApiResponse<T>(
val success: Boolean = true,
val data: T? = null,
val error: ApiErrorResponse? = null
) {
companion object {
fun success(): ApiResponse<Unit> {
return ApiResponse(success = true, data = null)
}
fun <T> success(data: T): ApiResponse<T> {
return ApiResponse(success = true, data = data)
}
fun fail(
exceptionType: WithaengExceptionType,
message: String?
): ApiResponse<Unit> {
return ApiResponse(
success = false,
data = null,
error = ApiErrorResponse(
code = exceptionType.errorCode,
message = message ?: exceptionType.message
)
)
}
}
}
data class ApiErrorResponse(val code: String, val message: String?) | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/common/ApiResponse.kt | 4141397402 |
package com.travel.withaeng.common
object Constants {
object Authentication {
const val BEARER_TYPE = "Bearer"
const val BEARER_TOKEN_PREFIX_WITH_WHITESPACE = "$BEARER_TYPE "
}
} | withaeng-backend/withaeng-api/src/main/kotlin/com/travel/withaeng/common/Constants.kt | 1677082498 |
package com.travel.withaeng.external.ses.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.thymeleaf.TemplateEngine
import org.thymeleaf.spring6.SpringTemplateEngine
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver
import org.thymeleaf.templatemode.TemplateMode
@Configuration
class ThymeleafConfig {
@Bean
fun htmlTemplateEngine(springResourceTemplateResolver: SpringResourceTemplateResolver): TemplateEngine {
return SpringTemplateEngine().apply {
addTemplateResolver(springResourceTemplateResolver)
}
}
@Bean
fun springResourceTemplateResolver(): SpringResourceTemplateResolver {
return SpringResourceTemplateResolver().apply {
prefix = TEMPLATE_PREFIX
characterEncoding = TEMPLATE_CHARACTER_ENCODING
suffix = TEMPLATE_SUFFIX
templateMode = TemplateMode.HTML
isCacheable = false
}
}
companion object {
private const val TEMPLATE_PREFIX = "classpath:templates/"
private const val TEMPLATE_CHARACTER_ENCODING = "UTF-8"
private const val TEMPLATE_SUFFIX = ".html"
}
} | withaeng-backend/withaeng-external/src/main/kotlin/com/travel/withaeng/external/ses/config/ThymeleafConfig.kt | 1539299444 |
package com.travel.withaeng.external.ses.config
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.regions.Regions
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
// TODO: Device SES Config from development environment (local or prod)
class SESConfig {
@Value("\${cloud.aws.credentials.access-key}")
private lateinit var accessKey: String
@Value("\${cloud.aws.credentials.secret-key}")
private lateinit var secretKey: String
@Value("\${cloud.aws.region.static}")
private lateinit var regionName: String
@Bean
fun amazonSimpleEmailService(): AmazonSimpleEmailService {
val credentials = BasicAWSCredentials(accessKey, secretKey)
return AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.fromName(regionName))
.withCredentials(AWSStaticCredentialsProvider(credentials))
.build()
}
} | withaeng-backend/withaeng-external/src/main/kotlin/com/travel/withaeng/external/ses/config/SESConfig.kt | 3537622537 |
package com.travel.withaeng.external.ses
interface MailSender {
fun send(subject: String, variables: Map<String, Any>, vararg to: String)
} | withaeng-backend/withaeng-external/src/main/kotlin/com/travel/withaeng/external/ses/MailSender.kt | 3207198739 |
package com.travel.withaeng.external.ses
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService
import com.amazonaws.services.simpleemail.model.*
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
import java.nio.charset.StandardCharsets
@Service
class MailSenderImpl(private val emailService: AmazonSimpleEmailService, private val templateEngine: TemplateEngine) :
MailSender {
@Value("\${cloud.aws.ses.from}")
private lateinit var from: String
override fun send(subject: String, variables: Map<String, Any>, vararg to: String) {
val content = templateEngine.process("email-template", createContext(variables))
val request = createSendEmailRequest(subject, content, *to)
emailService.sendEmail(request)
}
private fun createContext(variables: Map<String, Any>): Context {
return Context().apply { setVariables(variables) }
}
private fun createSendEmailRequest(subject: String, content: String, vararg to: String): SendEmailRequest {
return SendEmailRequest()
.withDestination(Destination().withToAddresses(*to))
.withSource(from)
.withMessage(
Message()
.withSubject(Content().withCharset(StandardCharsets.UTF_8.name()).withData(subject))
.withBody(Body().withHtml(Content().withCharset(StandardCharsets.UTF_8.name()).withData(content)))
)
}
} | withaeng-backend/withaeng-external/src/main/kotlin/com/travel/withaeng/external/ses/MailSenderImpl.kt | 875501023 |
class Electrodomestic(
private var nom: String = "",
private var preuBase: Int = 0,
private var color: String = "blanc",
private var consum: String = "G",
private var pes: Int = 5,
private var càrrega: Int = 5,
private var mida: Int = 28
) {
fun preuFinal(): Int {
var preuFinal = preuBase
when (consum) {
"A" -> preuFinal += 35
"B" -> preuFinal += 30
"C" -> preuFinal += 25
"D" -> preuFinal += 20
"E" -> preuFinal += 15
"F" -> preuFinal += 10
"G" -> preuFinal += 0
}
when {
pes in 6..20 -> preuFinal += 20
pes in 21..50 -> preuFinal += 50
pes in 51..80 -> preuFinal += 80
pes > 80 -> preuFinal += 100
}
if (càrrega in 6..10) {
preuFinal += when (càrrega) {
in 6..7 -> 55
8 -> 70
9 -> 85
10 -> 100
else -> 0
}
}
if (mida in 29..50) {
preuFinal += when {
mida in 29..32 -> 50
mida in 33..42 -> 100
mida in 43..50 -> 150
mida >= 51 -> 200
else -> 0
}
}
return preuFinal
}
override fun toString(): String {
return when {
càrrega > 0 -> "Rentadora: Nom=$nom, PreuBase=$preuBase, Color=$color, Consum=$consum, Pes=$pes, Càrrega=$càrrega"
else -> "Televisió: Nom=$nom, PreuBase=$preuBase, Color=$color, Consum=$consum, Pes=$pes, Mida=$mida”"
}
}
} | Electrodomesticos/src/main/kotlin/electrodomesticos.kt | 3159145807 |
fun main() {
val electrodomestic1 = Electrodomestic("Lavadora Bosch", 25, "blanc", "A", 2)
val electrodomestic2 = Electrodomestic("Cafetera Krups", 33, "platejat", "C", 15)
println(electrodomestic1.toString())
println(electrodomestic2.toString())
println("Preu final electrodomestic1: ${electrodomestic1.preuFinal()}€")
println("Preu final electrodomestic2: ${electrodomestic2.preuFinal()}€")
} | Electrodomesticos/src/main/kotlin/Main.kt | 2926224258 |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* 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 com.example.tiptime.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF984061)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFFFD9E2)
val md_theme_light_onPrimaryContainer = Color(0xFF3E001D)
val md_theme_light_secondary = Color(0xFF754B9C)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFF1DBFF)
val md_theme_light_onSecondaryContainer = Color(0xFF2D0050)
val md_theme_light_tertiary = Color(0xFF984060)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFD9E2)
val md_theme_light_onTertiaryContainer = Color(0xFF3E001D)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFAFCFF)
val md_theme_light_onBackground = Color(0xFF001F2A)
val md_theme_light_surface = Color(0xFFFAFCFF)
val md_theme_light_onSurface = Color(0xFF001F2A)
val md_theme_light_surfaceVariant = Color(0xFFF2DDE2)
val md_theme_light_onSurfaceVariant = Color(0xFF514347)
val md_theme_light_outline = Color(0xFF837377)
val md_theme_light_inverseOnSurface = Color(0xFFE1F4FF)
val md_theme_light_inverseSurface = Color(0xFF003547)
val md_theme_light_inversePrimary = Color(0xFFFFB0C8)
val md_theme_light_surfaceTint = Color(0xFF984061)
val md_theme_light_outlineVariant = Color(0xFFD5C2C6)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFFFB0C8)
val md_theme_dark_onPrimary = Color(0xFF5E1133)
val md_theme_dark_primaryContainer = Color(0xFF7B2949)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E2)
val md_theme_dark_secondary = Color(0xFFDEB7FF)
val md_theme_dark_onSecondary = Color(0xFF44196A)
val md_theme_dark_secondaryContainer = Color(0xFF5C3382)
val md_theme_dark_onSecondaryContainer = Color(0xFFF1DBFF)
val md_theme_dark_tertiary = Color(0xFFFFB1C7)
val md_theme_dark_onTertiary = Color(0xFF5E1132)
val md_theme_dark_tertiaryContainer = Color(0xFF7B2948)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFD9E2)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF001F2A)
val md_theme_dark_onBackground = Color(0xFFBFE9FF)
val md_theme_dark_surface = Color(0xFF001F2A)
val md_theme_dark_onSurface = Color(0xFFBFE9FF)
val md_theme_dark_surfaceVariant = Color(0xFF514347)
val md_theme_dark_onSurfaceVariant = Color(0xFFD5C2C6)
val md_theme_dark_outline = Color(0xFF9E8C90)
val md_theme_dark_inverseOnSurface = Color(0xFF001F2A)
val md_theme_dark_inverseSurface = Color(0xFFBFE9FF)
val md_theme_dark_inversePrimary = Color(0xFF984061)
val md_theme_dark_surfaceTint = Color(0xFFFFB0C8)
val md_theme_dark_outlineVariant = Color(0xFF514347)
val md_theme_dark_scrim = Color(0xFF000000)
| Tipulator/app/src/main/java/com/example/tiptime/ui/theme/Color.kt | 3409203932 |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* 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 com.example.tiptime.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun TipTimeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
// Dynamic color in this app is turned off for learning purposes
dynamicColor: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| Tipulator/app/src/main/java/com/example/tiptime/ui/theme/Theme.kt | 3312208453 |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* 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 com.example.tiptime.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
displaySmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 36.sp,
lineHeight = 44.sp,
letterSpacing = 0.sp,
)
)
| Tipulator/app/src/main/java/com/example/tiptime/ui/theme/Type.kt | 2149473445 |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* 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 com.example.tiptime
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.tiptime.ui.theme.TipTimeTheme
import java.text.NumberFormat
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
TipTimeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
) {
TipTimeLayout()
}
}
}
}
}
@Composable
fun TipTimeLayout() {
var amountInput by remember { mutableStateOf("") }
var tipInput by remember { mutableStateOf("") }
val tipPercent = tipInput.toDoubleOrNull() ?: 0.0
val amount = amountInput.toDoubleOrNull() ?: 0.0
var roundUp by remember { mutableStateOf(false) }
val tip = calculateTip(amount, tipPercent, roundUp)
Column(
modifier = Modifier
.statusBarsPadding()
.padding(horizontal = 40.dp)
.verticalScroll(rememberScrollState())
.safeDrawingPadding(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = stringResource(R.string.calculate_tip),
modifier = Modifier
.padding(bottom = 16.dp, top = 40.dp)
.align(alignment = Alignment.Start)
)
EditNumberField(
label = R.string.bill_amount,
value = amountInput,
onValueChange = { amountInput = it },
leadingIcon = R.drawable.money,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
modifier = Modifier
.padding(bottom = 32.dp)
.fillMaxWidth()
)
EditNumberField(
label = R.string.how_was_the_service,
value = tipInput,
leadingIcon = R.drawable.percent,
onValueChange = { tipInput = it },
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
modifier = Modifier
.padding(bottom = 32.dp)
.fillMaxWidth()
)
RoundTheTipRow(
roundUp = roundUp,
onRoundUpChanged = { roundUp = it },
modifier = Modifier.padding(bottom = 32.dp)
)
Text(
text = stringResource(R.string.tip_amount, tip),
style = MaterialTheme.typography.displaySmall
)
Spacer(modifier = Modifier.height(150.dp))
}
}
@Composable
fun EditNumberField(
@StringRes label: Int,
@DrawableRes leadingIcon: Int,
keyboardOptions: KeyboardOptions,
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier
) {
TextField(
value = value,
leadingIcon = { Icon(painter = painterResource(id = leadingIcon), null) },
onValueChange = onValueChange,
label = { Text(stringResource(label)) },
singleLine = true,
keyboardOptions = keyboardOptions,
modifier = modifier
)
}
@Composable
fun RoundTheTipRow(
roundUp: Boolean,
onRoundUpChanged: (Boolean) -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.size(48.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = stringResource(R.string.round_up_tip))
Switch(
checked = roundUp,
onCheckedChange = onRoundUpChanged,
modifier = modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.End),
)
}
}
/**
* Calculates the tip based on the user input and format the tip amount
* according to the local currency.
* Example would be "$10.00".
*/
private fun calculateTip(amount: Double,
tipPercent: Double = 15.0,
roundUp: Boolean
): String {
var tip = tipPercent / 100 * amount
if (roundUp) {
tip = kotlin.math.ceil(tip)
}
return NumberFormat.getCurrencyInstance().format(tip)
}
@Preview(showBackground = true)
@Composable
fun TipTimeLayoutPreview() {
TipTimeTheme {
TipTimeLayout()
}
}
| Tipulator/app/src/main/java/com/example/tiptime/MainActivity.kt | 4166179568 |
package com.example.tourismapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.tourismapp", appContext.packageName)
}
} | Cultoura-BitBandits-Vihaan007/app/src/androidTest/java/com/example/tourismapp/ExampleInstrumentedTest.kt | 2072873846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.