content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.posts.models
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import java.time.Instant
data class PostDTO(
@JsonProperty("titulo")
val title: String,
@JsonProperty("contenido")
val content: String,
@JsonProperty("fecha_creacion")
val createdAt: Instant,
@JsonProperty("fecha_actualizacion")
val updatedAt: Instant,
@JsonIgnore
val categoryId: Long
) | postsproject/src/main/kotlin/com/example/posts/models/PostDTO.kt | 2370398153 |
package com.example.posts.models
import com.fasterxml.jackson.annotation.JsonBackReference
import com.fasterxml.jackson.annotation.JsonManagedReference
import jakarta.persistence.*
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
import java.time.Instant
@Entity
@Table(name = "post")
data class Post(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoria_id", nullable = false)
@JsonBackReference
val category: Category,
@Column(name = "titulo", nullable = false, length = 150)
val title: String,
@Column(name = "contenido", nullable = false, columnDefinition = "TEXT")
val content: String,
@Column(name = "fecha_creacion", nullable = false)
@CreationTimestamp
val createdAt: Instant,
@Column(name = "fecha_actualizacion", nullable = false)
@UpdateTimestamp
val updatedAt: Instant,
@OneToMany(mappedBy = "post", cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
@JsonManagedReference
val comments: List<Comment> = mutableListOf()
)
| postsproject/src/main/kotlin/com/example/posts/models/Post.kt | 2413830570 |
package com.example.posts.models
import com.fasterxml.jackson.annotation.JsonProperty
import java.time.Instant
data class CategoryDTO(
@JsonProperty("nombre")
val name: String,
@JsonProperty("fecha_creacion")
val createdAt: Instant,
@JsonProperty("fecha_actualizacion")
val updatedAt: Instant,
) | postsproject/src/main/kotlin/com/example/posts/models/CategoryDTO.kt | 2644389493 |
package com.example.posts.controllers
import com.example.posts.models.Post
import com.example.posts.services.PostServiceImpl
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/posts")
class PostController(private val postServiceImpl: PostServiceImpl) {
@PostMapping
fun createPost(@RequestBody post: Post): ResponseEntity<Post> {
val savedPost = postServiceImpl.createPost(post)
return ResponseEntity.ok(savedPost)
}
@GetMapping("/{id}")
fun getPost(@PathVariable id: Long): ResponseEntity<Post> {
val post = postServiceImpl.getPostById(id)
return ResponseEntity.ok(post)
}
@PutMapping("/{id}")
fun updatePost(@PathVariable id: Long, @RequestBody post: Post): ResponseEntity<Post> {
val updatedPost = postServiceImpl.updatePost(id, post)
return ResponseEntity.ok(updatedPost)
}
@DeleteMapping("/{id}")
fun deletePost(@PathVariable id: Long): ResponseEntity<Void> {
postServiceImpl.deletePost(id)
return ResponseEntity.noContent().build()
}
@GetMapping
fun getAllPosts(): ResponseEntity<List<Post>> {
val posts = postServiceImpl.getAllPosts()
return ResponseEntity.ok(posts)
}
}
| postsproject/src/main/kotlin/com/example/posts/controllers/PostController.kt | 2688886354 |
package com.example.posts.controllers
import com.example.posts.models.Category
import com.example.posts.models.CategoryDTO
import com.example.posts.services.CategoryServiceImpl
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/categories")
class CategoryController(private val categoryServiceImpl: CategoryServiceImpl) {
@PostMapping
fun createCategory(@RequestBody categoryDTO: CategoryDTO): ResponseEntity<CategoryDTO> {
val savedCategory = categoryServiceImpl.createCategory(categoryDTO)
return ResponseEntity.ok(savedCategory)
}
@GetMapping("/{id}")
fun getCategory(@PathVariable id: Long): ResponseEntity<CategoryDTO> {
val category = categoryServiceImpl.getCategoryById(id)
return ResponseEntity.ok(category)
}
@PutMapping("/{id}")
fun updateCategory(@PathVariable id: Long, @RequestBody category: CategoryDTO): ResponseEntity<CategoryDTO> {
val updatedCategory = categoryServiceImpl.updateCategory(id, category)
return ResponseEntity.ok(updatedCategory)
}
@DeleteMapping("/{id}")
fun deleteCategory(@PathVariable id: Long): ResponseEntity<Void> {
categoryServiceImpl.deleteCategory(id)
return ResponseEntity.noContent().build()
}
@GetMapping
fun getAllCategories(): ResponseEntity<List<CategoryDTO>> {
val categories = categoryServiceImpl.getAllCategories()
return ResponseEntity.ok(categories)
}
}
| postsproject/src/main/kotlin/com/example/posts/controllers/CategoryController.kt | 219210693 |
package com.example.posts.controllers
import com.example.posts.models.Comment
import com.example.posts.models.CommentDTO
import com.example.posts.services.CommentServiceImpl
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/comments")
class CommentController(private val commentServiceImpl: CommentServiceImpl) {
@PostMapping
fun createComment(@RequestBody commentDTO: CommentDTO): ResponseEntity<CommentDTO> {
val savedComment = commentServiceImpl.createComment(commentDTO)
return ResponseEntity.ok(savedComment)
}
@GetMapping("/{id}")
fun getComment(@PathVariable id: Long): ResponseEntity<CommentDTO> {
val comment = commentServiceImpl.getCommentById(id)
return ResponseEntity.ok(comment)
}
@PutMapping("/{id}")
fun updateComment(@PathVariable id: Long, @RequestBody commentDTO: CommentDTO): ResponseEntity<CommentDTO> {
val updatedComment = commentServiceImpl.updateComment(id, commentDTO)
return ResponseEntity.ok(updatedComment)
}
@DeleteMapping("/{id}")
fun deleteComment(@PathVariable id: Long): ResponseEntity<Void> {
commentServiceImpl.deleteComment(id)
return ResponseEntity.noContent().build()
}
@GetMapping
fun getAllComments(): ResponseEntity<List<CommentDTO>> {
val comments = commentServiceImpl.getAllComments()
return ResponseEntity.ok(comments)
}
}
| postsproject/src/main/kotlin/com/example/posts/controllers/CommentController.kt | 3051486628 |
package com.example.posts.services
import com.example.posts.models.CategoryDTO
import com.example.posts.models.Comment
import com.example.posts.models.CommentDTO
import com.example.posts.repositories.CommentRepository
import com.example.posts.repositories.PostRepository
import org.springframework.stereotype.Service
import java.time.Instant
@Service
class CommentServiceImpl(
private val commentRepository: CommentRepository,
private val postRepository: PostRepository
) : CommentService {
override fun createComment(commentDTO: CommentDTO): CommentDTO {
val newComment = Comment(
content = commentDTO.content,
createdAt = Instant.now(),
updatedAt = Instant.now(),
post = postRepository.findById(commentDTO.postId).orElseThrow { RuntimeException("Post not found") }
);
commentRepository.save(newComment)
return CommentDTO(
content = newComment.content,
createdAt = newComment.createdAt,
updatedAt = newComment.updatedAt,
postId = newComment.post.id
)
}
override fun getCommentById(id: Long): CommentDTO {
val comment = commentRepository.findById(id).orElseThrow { RuntimeException("Comment not found") }
return CommentDTO(
content = comment.content,
createdAt = comment.createdAt,
updatedAt = comment.updatedAt,
postId = comment.post.id
)
}
override fun updateComment(id: Long, commentDTO: CommentDTO): CommentDTO {
val existingComment = commentRepository.findById(id).orElseThrow { RuntimeException("Comment not found") }
val updatedComment = existingComment.copy(
content = commentDTO.content
)
val saveComment = commentRepository.save(updatedComment);
return CommentDTO(
content = saveComment.content,
createdAt = saveComment.createdAt,
updatedAt = saveComment.updatedAt,
postId = saveComment.id
)
}
override fun deleteComment(id: Long) {
val comment = commentRepository.findById(id).orElseThrow { RuntimeException("Comment not found") }
commentRepository.delete(comment)
}
override fun getAllComments(): List<CommentDTO> {
val comments = commentRepository.findAll()
return comments.map { comment ->
CommentDTO(
content = comment.content,
createdAt = comment.createdAt,
updatedAt = comment.updatedAt,
postId = comment.id
)
}
}
}
| postsproject/src/main/kotlin/com/example/posts/services/CommentServiceImpl.kt | 2302069103 |
package com.example.posts.services
import com.example.posts.models.CommentDTO
import com.example.posts.models.Post
import com.example.posts.models.PostDTO
import com.example.posts.repositories.CategoryRepository
import com.example.posts.repositories.CommentRepository
import com.example.posts.repositories.PostRepository
import org.springframework.stereotype.Service
@Service
class PostServiceImpl(
private val postRepository: PostRepository,
private val categoryRepository: CategoryRepository
) : PostService {
override fun createPost(postDTO: PostDTO): PostDTO {
val newPost = Post(
title = postDTO.title,
content = postDTO.content,
createdAt = postDTO.createdAt,
updatedAt = postDTO.updatedAt,
category = categoryRepository.findById(postDTO.categoryId).orElseThrow { RuntimeException("Post not found") }
)
postRepository.save(newPost);
return PostDTO(
title = newPost.title,
content = newPost.content,
createdAt = newPost.createdAt,
updatedAt = newPost.updatedAt,
categoryId = newPost.category.id
)
}
override fun getPostById(id: Long): PostDTO {
val post = postRepository.findById(id).orElseThrow { RuntimeException("Post not found") };
return PostDTO(
title = post.title,
content = post.content,
createdAt = post.createdAt,
updatedAt = post.updatedAt,
categoryId = post.category.id
)
}
override fun updatePost(id: Long, postDTO: PostDTO): PostDTO {
val existingPost = postRepository.findById(id).orElseThrow { RuntimeException("Post not found") };
val updatedPost = existingPost.copy(
title = postDTO.title,
content = postDTO.content,
)
val savePost = postRepository.save(updatedPost);
return PostDTO(
title = savePost.title,
content = savePost.content,
createdAt = savePost.createdAt,
updatedAt = savePost.updatedAt,
categoryId = savePost.category.id
)
}
override fun deletePost(id: Long) {
val post = postRepository.findById(id).orElseThrow { RuntimeException("Post not found") };
postRepository.delete(post)
}
override fun getAllPosts(): List<PostDTO> {
val posts = postRepository.findAll()
return posts.map { post ->
PostDTO(
title = post.title,
content = post.content,
createdAt = post.createdAt,
updatedAt = post.updatedAt,
categoryId = post.category.id
)
}
}
}
| postsproject/src/main/kotlin/com/example/posts/services/PostServiceImpl.kt | 2894557860 |
package com.example.posts.services
import com.example.posts.models.Comment
import com.example.posts.models.CommentDTO
interface CommentService {
fun createComment(commentDTO: CommentDTO): CommentDTO
fun getCommentById(id: Long): CommentDTO
fun updateComment(id: Long, commentDTO: CommentDTO): CommentDTO
fun deleteComment(id: Long)
fun getAllComments(): List<CommentDTO>
} | postsproject/src/main/kotlin/com/example/posts/services/CommentService.kt | 2420801231 |
package com.example.posts.services
import com.example.posts.models.Post
import com.example.posts.models.PostDTO
interface PostService {
fun createPost(postDTO: PostDTO): PostDTO
fun getPostById(id: Long): PostDTO
fun updatePost(id: Long, postDTO: PostDTO): PostDTO
fun deletePost(id: Long)
fun getAllPosts(): List<PostDTO>
} | postsproject/src/main/kotlin/com/example/posts/services/PostService.kt | 4160430007 |
package com.example.posts.services
import com.example.posts.models.Category
import com.example.posts.models.CategoryDTO
interface CategoryService {
fun createCategory(categoryDTO: CategoryDTO): CategoryDTO
fun getCategoryById(id: Long): CategoryDTO
fun updateCategory(id: Long, categoryDTO: CategoryDTO): CategoryDTO
fun deleteCategory(id: Long)
fun getAllCategories(): List<CategoryDTO>
} | postsproject/src/main/kotlin/com/example/posts/services/CategoryService.kt | 2019217802 |
package com.example.posts.services
import com.example.posts.models.Category
import com.example.posts.models.CategoryDTO
import com.example.posts.models.PostDTO
import com.example.posts.repositories.CategoryRepository
import org.springframework.stereotype.Service
import java.time.Instant
@Service
class CategoryServiceImpl(private val categoryRepository: CategoryRepository) : CategoryService{
override fun createCategory(categoryDTO: CategoryDTO): CategoryDTO {
val newCategory = Category(
name = categoryDTO.name,
createdAt = Instant.now(),
updatedAt = Instant.now()
);
categoryRepository.save(newCategory);
return CategoryDTO(
name = newCategory.name,
createdAt = newCategory.createdAt,
updatedAt = newCategory.updatedAt,
)
}
override fun getCategoryById(id: Long): CategoryDTO {
val category = categoryRepository.findById(id).orElseThrow { RuntimeException("Category not found") }
return CategoryDTO(
name = category.name,
createdAt = category.createdAt,
updatedAt = category.updatedAt,
)
}
override fun updateCategory(id: Long, categoryDTO: CategoryDTO): CategoryDTO {
val existingCategory = categoryRepository.findById(id).orElseThrow { RuntimeException("Category not found") }
val updatedCategory = existingCategory.copy(
name = categoryDTO.name
)
val saveCategory = categoryRepository.save(updatedCategory)
return CategoryDTO(
name = saveCategory.name,
createdAt = saveCategory.createdAt,
updatedAt = saveCategory.updatedAt,
)
}
override fun deleteCategory(id: Long) {
val category = categoryRepository.findById(id).orElseThrow { RuntimeException("Category not found") }
categoryRepository.delete(category)
}
override fun getAllCategories(): List<CategoryDTO> {
val categories = categoryRepository.findAll()
return categories.map { category ->
CategoryDTO(
name = category.name,
createdAt = category.createdAt,
updatedAt = category.updatedAt,
)
}
}
}
| postsproject/src/main/kotlin/com/example/posts/services/CategoryServiceImpl.kt | 4199219641 |
package com.example.tugas1_71210778
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.tugas1_71210778", appContext.packageName)
}
} | Latihan1_71210778/app/src/androidTest/java/com/example/tugas1_71210778/ExampleInstrumentedTest.kt | 3133986169 |
package com.example.tugas1_71210778
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)
}
} | Latihan1_71210778/app/src/test/java/com/example/tugas1_71210778/ExampleUnitTest.kt | 2297329164 |
package com.example.tugas1_71210778
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Latihan1_71210778/app/src/main/java/com/example/tugas1_71210778/MainActivity.kt | 1834094052 |
package com.example.belajarfisika
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.belajarfisika", appContext.packageName)
}
} | FIsika-Application-Project/app/src/androidTest/java/com/example/belajarfisika/ExampleInstrumentedTest.kt | 2985318470 |
package com.example.belajarfisika
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)
}
} | FIsika-Application-Project/app/src/test/java/com/example/belajarfisika/ExampleUnitTest.kt | 3433775178 |
package com.example.belajarfisika
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
class ContentActivity1 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content1)
val viewPager: ViewPager = findViewById(R.id.viewPager)
val adapter = MyPagerAdapter(supportFragmentManager)
viewPager.adapter = adapter
}
fun openNextActivity1(view: View) {
onBackPressed()
}
private class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> ExplanationFragment1()
1 -> CalculatorFragment1()
else -> throw IllegalArgumentException("Invalid position")
}
}
override fun getCount(): Int {
return 2 // Jumlah slide yang ingin ditampilkan
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ContentActivity1.kt | 1092900377 |
package com.example.belajarfisika
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
private lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.logintheme)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.btn_1)
button.setOnClickListener {
val Intent = Intent(this@MainActivity, HomeActivity::class.java)
startActivity(Intent)
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/MainActivity.kt | 1437026255 |
package com.example.belajarfisika
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.VideoView
import android.widget.MediaController
class ExplanationFragment1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_explanation1, container, false)
val videoView = rootView.findViewById<VideoView>(R.id.videoView)
val videoPath = "android.resource://" + requireActivity().packageName + "/" + R.raw.kasus_1
val videoUri = Uri.parse(videoPath)
videoView.setVideoURI(videoUri)
val mediaController = MediaController(requireContext())
mediaController.setAnchorView(videoView)
videoView.setMediaController(mediaController)
return rootView
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ExplanationFragment1.kt | 535008406 |
package com.example.belajarfisika
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
class CalculatorFragment1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_calculator1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val editText1 = view.findViewById<EditText>(R.id.editText1)
val editText2 = view.findViewById<EditText>(R.id.editText2)
val textResult = view.findViewById<TextView>(R.id.result)
val spinnerOperation = view.findViewById<Spinner>(R.id.select)
val buttonCalculate = view.findViewById<Button>(R.id.buttonCalculator)
val defaultUnderlineColor = ViewCompat.getBackgroundTintList(editText1)?.defaultColor
editText1.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
ViewCompat.setBackgroundTintList(editText1, ContextCompat.getColorStateList(requireContext(), R.color.underline_color))
} else {
ViewCompat.setBackgroundTintList(editText1, ContextCompat.getColorStateList(requireContext(), defaultUnderlineColor ?: R.color.default_underline_color))
}
}
editText2.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
ViewCompat.setBackgroundTintList(editText2, ContextCompat.getColorStateList(requireContext(), R.color.underline_color))
} else {
ViewCompat.setBackgroundTintList(editText2, ContextCompat.getColorStateList(requireContext(), defaultUnderlineColor ?: R.color.default_underline_color))
}
}
val adapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.select1,
android.R.layout.simple_spinner_item
)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerOperation.adapter = adapter
spinnerOperation.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long) {
when (position) {
0 -> {
editText1.hint = "masukkan nilai F (gaya) dalam satuan Newton"
editText2.hint = "masukkan nilai s (jarak) dalam satuan Meter"
}
1 -> {
editText1.hint = "masukkan nilai W (usaha) dalam satuan Joule"
editText2.hint = "masukkan nilai s (jarak) dalam satuan Meter"
}
2 -> {
editText1.hint = "masukkan nilai W (usaha) dalam satuan Joule"
editText2.hint = "masukkan nilai F (gaya) dalam satuan Newton"
}
}
}
override fun onNothingSelected(parentView: AdapterView<*>?) {
// Do nothing here
}
}
buttonCalculate.setOnClickListener {
val x = editText1.text.toString().toDoubleOrNull()
val y = editText2.text.toString().toDoubleOrNull()
val selectedOperation = spinnerOperation.selectedItem.toString()
if (x == null || y == null) {
editText1.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.colorError)
editText2.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.colorError)
textResult.visibility = View.VISIBLE
textResult.text = "Masukkan value dengan benar!!"
textResult.setBackgroundResource(R.drawable.resulterror)
textResult.setTextAppearance(R.style.errorResult)
Toast.makeText(requireContext(), "Error = Invalid value!!" ,Toast.LENGTH_SHORT).show()
} else {
val result = when (selectedOperation) {
"Rumus Usaha" -> x * y
"Rumus Gaya" -> if (y != 0.0) x / y else 0.0
"Rumus Jarak" -> if (y != 0.0) x / y else 0.0
else -> 0.0
}
val unit = when (selectedOperation) {
"Rumus Usaha" -> "Joule"
"Rumus Gaya" -> "Newton"
"Rumus Jarak" -> "Meter"
else -> ""
}
val operationSymbol = when (selectedOperation) {
"Rumus Usaha" -> "Usaha (W)"
"Rumus Gaya" -> "Gaya (F)"
"Rumus Jarak" -> "Jarak (S)"
else -> ""
}
textResult.setBackgroundResource(R.drawable.result)
textResult.setTextAppearance(R.style.defaultResult)
editText1.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.default_underline_color)
editText2.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.default_underline_color)
textResult.text = "Hasil = $result $unit"
textResult.visibility = View.VISIBLE
Toast.makeText(requireContext(), "$operationSymbol = $result", Toast.LENGTH_SHORT).show()
}
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/CalculatorFragment1.kt | 1864675140 |
package com.example.belajarfisika
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.FrameLayout
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
val myFrameLayout: FrameLayout = findViewById(R.id.content1)
val myFrameLayout2: FrameLayout = findViewById(R.id.content2)
val myFrameLayout3: FrameLayout = findViewById(R.id.content3)
myFrameLayout.setOnClickListener {
val Intent = Intent(this, ContentActivity1::class.java)
startActivity(Intent)
}
myFrameLayout2.setOnClickListener {
val Intent = Intent(this, ContentActivity2::class.java)
startActivity(Intent)
}
myFrameLayout3.setOnClickListener {
val Intent = Intent(this, ContentActivity3::class.java)
startActivity(Intent)
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/HomeActivity.kt | 3062063424 |
package com.example.belajarfisika
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.VideoView
import android.widget.MediaController
class ExplanationFragment2 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_explanation2, container, false)
val videoView = rootView.findViewById<VideoView>(R.id.videoView)
val videoPath = "android.resource://" + requireActivity().packageName + "/" + R.raw.kasus_2
val videoUri = Uri.parse(videoPath)
videoView.setVideoURI(videoUri)
val mediaController = MediaController(requireContext())
mediaController.setAnchorView(videoView)
videoView.setMediaController(mediaController)
return rootView
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ExplanationFragment2.kt | 812491805 |
package com.example.belajarfisika
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
class ContentActivity3 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content3)
val viewPager: ViewPager = findViewById(R.id.slidecontent3)
val adapter = MyPagerAdapter(supportFragmentManager)
viewPager.adapter = adapter
}
fun openNextActivity3(view: View) {
onBackPressed()
}
private class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> ExplanationFragment3()
1 -> CalculatorFragment3()
else -> throw IllegalArgumentException("Invalid position")
}
}
override fun getCount(): Int {
return 2
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ContentActivity3.kt | 3600250060 |
package com.example.belajarfisika
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
class CalculatorFragment2 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_calculator2, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val editText1 = view.findViewById<EditText>(R.id.editText1)
val textResult = view.findViewById<TextView>(R.id.result)
val defaultUnderlineColor = ViewCompat.getBackgroundTintList(editText1)?.defaultColor
editText1.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
ViewCompat.setBackgroundTintList(editText1, ContextCompat.getColorStateList(requireContext(), R.color.underline_color))
} else {
ViewCompat.setBackgroundTintList(editText1, ContextCompat.getColorStateList(requireContext(), defaultUnderlineColor ?: R.color.default_underline_color))
}
}
val buttonCalculate = view.findViewById<Button>(R.id.buttonCalculator)
buttonCalculate.setOnClickListener {
outputMain(editText1.text.toString(), textResult)
}
}
private fun countFaksi(input: Double): Double {
return -input
}
private fun outputMain(inputText: String, textResult: TextView) {
val editText1 = view?.findViewById<EditText>(R.id.editText1)
if (inputText.isNotEmpty()) {
val result = countFaksi(inputText.toDouble())
textResult.text = "Hasil = $result Freaksi"
textResult.visibility = View.VISIBLE
textResult.setBackgroundResource(R.drawable.result)
textResult.setTextAppearance(R.style.defaultResult)
editText1?.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.default_underline_color)
Toast.makeText(requireContext(), "Faksi = $inputText > Freaksi = $result", Toast.LENGTH_SHORT).show()
} else {
textResult.text = "Input tidak boleh kosong!!"
textResult.visibility = View.VISIBLE
textResult.setBackgroundResource(R.drawable.resulterror)
textResult.setTextAppearance(R.style.errorResult)
editText1?.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.colorError)
Toast.makeText(requireContext(), "Error = Invalid value!!" ,Toast.LENGTH_SHORT).show()
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/CalculatorFragment2.kt | 2361415231 |
package com.example.belajarfisika
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
class CalculatorFragment3 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_calculator3, container, false)
val editText1 = view.findViewById<EditText>(R.id.editText1)
val editText2 = view.findViewById<EditText>(R.id.editText2)
val textResult = view.findViewById<TextView>(R.id.result)
val spinnerOperation = view.findViewById<Spinner>(R.id.select)
val buttonCalculator = view.findViewById<Button>(R.id.buttonCalculator)
val defaultUnderlineColor = ViewCompat.getBackgroundTintList(editText1)?.defaultColor
editText1.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
ViewCompat.setBackgroundTintList(
editText1,
ContextCompat.getColorStateList(requireContext(), R.color.underline_color)
)
} else {
ViewCompat.setBackgroundTintList(
editText1,
ContextCompat.getColorStateList(requireContext(), defaultUnderlineColor ?: R.color.default_underline_color)
)
}
}
editText2.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
ViewCompat.setBackgroundTintList(
editText2,
ContextCompat.getColorStateList(requireContext(), R.color.underline_color)
)
} else {
ViewCompat.setBackgroundTintList(
editText2,
ContextCompat.getColorStateList(requireContext(), defaultUnderlineColor ?: R.color.default_underline_color)
)
}
}
val adapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.select3,
android.R.layout.simple_spinner_item
)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerOperation.adapter = adapter
spinnerOperation.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long) {
when (position) {
0 -> {
editText1.hint = "masukkan nilai s (jarak) dalam satuan Meter"
editText2.hint = "masukkan nilai t (waktu) dalam satuan Second"
}
1 -> {
editText1.hint = "masukkan nilai v (kecepatan) dalam satuan m/s"
editText2.hint = "masukkan nilai t (waktu) dalam satuan Second"
}
2 -> {
editText1.hint = "masukkan nilai v (kecepatan) dalam satuan m/s"
editText2.hint = "masukkan nilai s (jarak) dalam satuan Meter"
}
}
}
override fun onNothingSelected(parentView: AdapterView<*>?) {
// Do nothing here
}
}
buttonCalculator.setOnClickListener {
val x = editText1.text.toString().toDoubleOrNull()
val y = editText2.text.toString().toDoubleOrNull()
val selectedOperation = spinnerOperation.selectedItem.toString()
if (x == null || y == null) {
editText1.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.colorError)
editText2.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.colorError)
textResult.visibility = View.VISIBLE
textResult.text = "Masukkan value dengan benar!!"
textResult.setBackgroundResource(R.drawable.resulterror)
textResult.setTextAppearance(R.style.errorResult)
Toast.makeText(requireContext(), "Error = Invalid value!!", Toast.LENGTH_SHORT).show()
} else {
val result = when (selectedOperation) {
"Rumus Kecepatan" -> if (y != 0.0) x / y else 0.0
"Rumus Jarak" -> x * y
"Rumus Waktu" -> if (y != 0.0) x / y else 0.0
else -> 0.0
}
val unit = when (selectedOperation) {
"Rumus Kecepatan" -> "m/s"
"Rumus Jarak" -> "Meter"
"Rumus Waktu" -> "Second"
else -> ""
}
val operationSymbol = when (selectedOperation) {
"Rumus Kecepatan" -> "kecepatan (v)"
"Rumus Jarak" -> "jarak (s)"
"Rumus Waktu" -> "waktu (t)"
else -> ""
}
textResult.setBackgroundResource(R.drawable.result)
textResult.setTextAppearance(R.style.defaultResult)
editText1.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.default_underline_color)
editText2.backgroundTintList = ContextCompat.getColorStateList(requireContext(), R.color.default_underline_color)
textResult.text = "Hasil = $result $unit"
textResult.visibility = View.VISIBLE
Toast.makeText(requireContext(), "$operationSymbol = $result", Toast.LENGTH_SHORT).show()
}
}
return view
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/CalculatorFragment3.kt | 3007263502 |
package com.example.belajarfisika
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.VideoView
import android.widget.MediaController
class ExplanationFragment3 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_explanation3, container, false)
val videoView = rootView.findViewById<VideoView>(R.id.videoView)
val videoPath = "android.resource://" + requireActivity().packageName + "/" + R.raw.kasus_3
val videoUri = Uri.parse(videoPath)
videoView.setVideoURI(videoUri)
val mediaController = MediaController(requireContext())
mediaController.setAnchorView(videoView)
videoView.setMediaController(mediaController)
return rootView
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ExplanationFragment3.kt | 2620962395 |
package com.example.belajarfisika
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
class ContentActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content2)
val viewPager: ViewPager = findViewById(R.id.slidecontent2)
val adapter = MyPagerAdapter(supportFragmentManager)
viewPager.adapter = adapter
}
fun openNextActivity2(view: View) {
onBackPressed()
}
private class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> ExplanationFragment2()
1 -> CalculatorFragment2()
else -> throw IllegalArgumentException("Invalid position")
}
}
override fun getCount(): Int {
return 2
}
}
} | FIsika-Application-Project/app/src/main/java/com/example/belajarfisika/ContentActivity2.kt | 3905951655 |
package com.jesusaledo.ac802
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.jesusaledo.ac802", appContext.packageName)
}
} | AC802/app/src/androidTest/java/com/jesusaledo/ac802/ExampleInstrumentedTest.kt | 2840993054 |
package com.jesusaledo.ac802
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)
}
} | AC802/app/src/test/java/com/jesusaledo/ac802/ExampleUnitTest.kt | 1671655897 |
package com.jesusaledo.ac802
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.widget.SearchView.OnQueryTextListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.jesusaledo.ac802.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity(), OnQueryTextListener {
private lateinit var binding: ActivityMainBinding
private lateinit var adapter: DogAdapter
private val dogImages = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.svDogs.setOnQueryTextListener(this)
initRecyclerView()
}
private fun initRecyclerView() {
adapter = DogAdapter(dogImages)
binding.rvDogs.layoutManager = LinearLayoutManager(this)
binding.rvDogs.adapter = adapter
}
private fun getRetroFit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://dog.ceo/api/breed/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private fun searchByName(query: String) {
CoroutineScope(Dispatchers.IO).launch {
val call = getRetroFit().create(APIService::class.java).getDogsByBreeds("$query/images")
val puppies: DogsResponse? = call.body()
runOnUiThread {
if (call.isSuccessful) {
val images = puppies?.images ?: emptyList()
dogImages.clear()
dogImages.addAll(images)
adapter.notifyDataSetChanged()
}
else
showError()
hideKeyboard()
}
}
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(binding.viewRoot.windowToken, 0)
}
private fun showError() {
Toast.makeText(this, "Ha ocurrido un error", Toast.LENGTH_SHORT).show()
}
override fun onQueryTextSubmit(query: String?): Boolean {
if (!query.isNullOrEmpty())
searchByName(query.toLowerCase())
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
} | AC802/app/src/main/java/com/jesusaledo/ac802/MainActivity.kt | 198450126 |
package com.jesusaledo.ac802
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.jesusaledo.ac802.databinding.ItemDogBinding
import com.squareup.picasso.Picasso
class DogViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val binding = ItemDogBinding.bind(view)
fun bind(image: String) {
Picasso.get().load(image).into(binding.ivDog)
}
} | AC802/app/src/main/java/com/jesusaledo/ac802/DogViewHolder.kt | 1115422768 |
package com.jesusaledo.ac802
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Url
interface APIService {
@GET
suspend fun getDogsByBreeds(@Url url: String): Response<DogsResponse>
} | AC802/app/src/main/java/com/jesusaledo/ac802/APIService.kt | 1769817966 |
package com.jesusaledo.ac802
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
class DogAdapter(val images: List<String>): RecyclerView.Adapter<DogViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DogViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return DogViewHolder(layoutInflater.inflate(R.layout.item_dog, parent, false))
}
override fun getItemCount(): Int = images.size
override fun onBindViewHolder(holder: DogViewHolder, position: Int) {
val item = images[position]
holder.bind(item)
}
} | AC802/app/src/main/java/com/jesusaledo/ac802/DogAdapter.kt | 525527327 |
package com.jesusaledo.ac802
import com.google.gson.annotations.SerializedName
data class DogsResponse (
@SerializedName("status") var status: String,
@SerializedName("message") var images: List<String>
) | AC802/app/src/main/java/com/jesusaledo/ac802/DogsResponse.kt | 3187573475 |
package ru.btpit.nmedia
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("ru.btpit.nmedia", appContext.packageName)
}
} | YP0_01.02/app/src/androidTest/java/ru/btpit/nmedia/ExampleInstrumentedTest.kt | 1791570383 |
package ru.btpit.nmedia
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)
}
} | YP0_01.02/app/src/test/java/ru/btpit/nmedia/ExampleUnitTest.kt | 1515901159 |
package ru.btpit.nmedia
import android.content.Intent
import android.media.Image
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.widget.PopupMenu
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import ru.btpit.nmedia.databinding.ActivityMainBinding
import ru.btpit.nmedia.databinding.PostCardBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding:ActivityMainBinding
private lateinit var navController : NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
mainActivity = this
navController = Navigation.findNavController(this, R.id.nav_host_fragment_container)
binding.bottomNavigationView.setupWithNavController(navController)
}
}
| YP0_01.02/app/src/main/java/ru/btpit/nmedia/MainActivity.kt | 2575996430 |
package ru.btpit.nmedia.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.viewModels
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import ru.btpit.nmedia.Post
import ru.btpit.nmedia.PostAdapter
import ru.btpit.nmedia.PostViewModel
import ru.btpit.nmedia.R
import ru.btpit.nmedia.databinding.FragmentListPostBinding
import ru.btpit.nmedia.databinding.PostCardBinding
import ru.btpit.nmedia.listPostFragment
import ru.btpit.nmedia.mainActivity
class ListPostFragment : Fragment(),PostAdapter.Listener {
private lateinit var binding:FragmentListPostBinding
val viewModel: PostViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentListPostBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listPostFragment = this
// isStartWhitShare()
val adapter = PostAdapter(this)
binding.imageButtonAddPost.setOnClickListener {
viewModel.addPost("")
binding.container.smoothScrollToPosition(0)
Toast.makeText(context,"Add",Toast.LENGTH_LONG).show()
}
binding.container.adapter = adapter
viewModel.data.observe(viewLifecycleOwner){post ->
adapter.submitList(post)
}
}
private fun isStartWhitShare(){
mainActivity.intent?.let {
if (it.action != Intent.ACTION_SEND)
return@let
val text = it.getStringExtra(Intent.EXTRA_TEXT)
if(text.isNullOrBlank())
{
Snackbar.make(binding.root, "Пусто лол", BaseTransientBottomBar.LENGTH_INDEFINITE)
.setAction("Окей"){
mainActivity.finish()
}.show()
return@let
}
Snackbar.make(binding.root, text, BaseTransientBottomBar.LENGTH_INDEFINITE).show()
viewModel.addPost(text)
it.action = Intent.ACTION_MAIN
}
}
override fun onClickLike(post: Post) {
viewModel.like(post.id)
}
override fun onClickRepost(post: Post) {
viewModel.repost(post.id)
val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, post.content)
type = "text/plain"
}
val shareIntent = Intent.createChooser(intent, "Поделиться")
startActivity(shareIntent)
}
override fun onClickMore(post: Post, view: View, binding: PostCardBinding) {
val popupMenu = android.widget.PopupMenu(context, view)
popupMenu.inflate(R.menu.more)
popupMenu.setOnMenuItemClickListener {
when(it.itemId)
{
R.id.menu_item_delete -> viewModel.removeById(post.id)
R.id.menu_item_edit -> editModeOn(binding,"")
}
true
}
popupMenu.show()
}
override fun cancelEditPost(post: Post, binding: PostCardBinding) {
with(binding)
{
editTextAutor.visibility = View.INVISIBLE
textViewAutor.visibility = View.VISIBLE
edittextcontent.visibility = View.INVISIBLE
textViewcontent.visibility = View.VISIBLE
edittexttg.visibility = View.INVISIBLE
textViewtg.visibility = View.VISIBLE
constraintEdit.visibility = View.GONE
ConstraintLayout5.visibility = View.VISIBLE
}
if(binding.editTextAutor.text.toString() == "" && binding.edittextcontent.text.toString() == "")
viewModel.removeById(post.id)
}
override fun saveEditPost(post: Post, binding: PostCardBinding) {
with(binding)
{
viewModel.editById(
post.id,
binding.editTextAutor.text.toString(),
binding.edittextcontent.text.toString(),
binding.edittexttg.text.toString()
)
}
cancelEditPost(post,binding)
}
override fun editModeOn(binding: PostCardBinding, content:String) {
with(binding)
{
editTextAutor.visibility = View.VISIBLE
textViewAutor.visibility = View.INVISIBLE
if (content!="")
edittextcontent.setText(content)
edittextcontent.visibility = View.VISIBLE
textViewcontent.visibility = View.INVISIBLE
edittexttg.visibility = View.VISIBLE
textViewtg.visibility = View.INVISIBLE
constraintEdit.visibility = View.VISIBLE
ConstraintLayout5.visibility = View.GONE
}
}
} | YP0_01.02/app/src/main/java/ru/btpit/nmedia/fragments/ListPostFragment.kt | 994540399 |
package ru.btpit.nmedia.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import ru.btpit.nmedia.Post
import ru.btpit.nmedia.PostAdapter
import ru.btpit.nmedia.PostViewModel
import ru.btpit.nmedia.R
import ru.btpit.nmedia.databinding.FragmentHomeBinding
import ru.btpit.nmedia.databinding.FragmentListPostBinding
import ru.btpit.nmedia.databinding.PostCardBinding
import ru.btpit.nmedia.homeFragment
import ru.btpit.nmedia.listPostFragment
class HomeFragment : Fragment(), PostAdapter.Listener {
lateinit var binding:FragmentHomeBinding
//private val viewModel: PostViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
homeFragment = this
val adapter = PostAdapter(this)
binding.container.adapter = adapter
listPostFragment.viewModel.data.observe(viewLifecycleOwner){post ->
adapter.submitList(post.filter { it.author == "Akiva" })
}
}
override fun onClickLike(post: Post) {
listPostFragment.viewModel.like(post.id)
}
override fun onClickRepost(post: Post) {
listPostFragment.viewModel.repost(post.id)
val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, post.content)
type = "text/plain"
}
val shareIntent = Intent.createChooser(intent, "Поделиться")
startActivity(shareIntent)
}
override fun onClickMore(post: Post, view: View, binding: PostCardBinding) {
val popupMenu = android.widget.PopupMenu(context, view)
popupMenu.inflate(R.menu.more)
popupMenu.setOnMenuItemClickListener {
when(it.itemId)
{
R.id.menu_item_delete -> listPostFragment.viewModel.removeById(post.id)
R.id.menu_item_edit -> editModeOn(binding,"")
}
true
}
popupMenu.show()
}
override fun cancelEditPost(post: Post, binding: PostCardBinding) {
with(binding)
{
editTextAutor.visibility = View.INVISIBLE
textViewAutor.visibility = View.VISIBLE
edittextcontent.visibility = View.INVISIBLE
textViewcontent.visibility = View.VISIBLE
edittexttg.visibility = View.INVISIBLE
textViewtg.visibility = View.VISIBLE
constraintEdit.visibility = View.GONE
ConstraintLayout5.visibility = View.VISIBLE
}
if(binding.editTextAutor.text.toString() == "" && binding.edittextcontent.text.toString() == "")
listPostFragment.viewModel.removeById(post.id)
}
override fun saveEditPost(post: Post, binding: PostCardBinding) {
with(binding)
{
listPostFragment.viewModel.editById(
post.id,
binding.editTextAutor.text.toString(),
binding.edittextcontent.text.toString(),
binding.edittexttg.text.toString()
)
}
cancelEditPost(post,binding)
}
override fun editModeOn(binding: PostCardBinding, content:String) {
with(binding)
{
editTextAutor.visibility = View.VISIBLE
textViewAutor.visibility = View.INVISIBLE
if (content!="")
edittextcontent.setText(content)
edittextcontent.visibility = View.VISIBLE
textViewcontent.visibility = View.INVISIBLE
edittexttg.visibility = View.VISIBLE
textViewtg.visibility = View.INVISIBLE
constraintEdit.visibility = View.VISIBLE
ConstraintLayout5.visibility = View.GONE
}
}
} | YP0_01.02/app/src/main/java/ru/btpit/nmedia/fragments/HomeFragment.kt | 26490321 |
package ru.btpit.nmedia
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import ru.btpit.nmedia.databinding.PostCardBinding
class PostDiffCallback : DiffUtil.ItemCallback<Post>(){
override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem.id==newItem.id
}
override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem == newItem
}
}
class PostViewHolder(private val binding: PostCardBinding):RecyclerView.ViewHolder(binding.root) {
fun bind(post: Post,listener: PostAdapter.Listener) {
binding.apply {
textViewAutor.text = post.author
editTextAutor.setText(post.author)
binding.root.setOnClickListener {
if (post.author == "Akiva")
it.findNavController().navigate(R.id.action_menu_item_post_to_menu_item_profil)
}
textViewPublshed.text = post.publish.split("GMT")[0]
imageButtonMenu.setOnClickListener{
listener.onClickMore(post,it, binding)
}
if (post.content=="")
textViewcontent.visibility = View.GONE
else
textViewcontent.visibility = View.VISIBLE
textViewcontent.text = post.content
edittextcontent.setText(post.content)
textViewAmountLike.text = convertToString(post.amountlike)
textViewAmountRepost.text = convertToString(post.amountRepost)
if (post.tg=="")
textView6.visibility = View.GONE
else {
textView6.text = post.tg
textView6.visibility = View.VISIBLE
}
if (post.tgS=="")
textViewtg.visibility = View.GONE
else
textViewtg.visibility = View.VISIBLE
textViewtg.text = post.tgS
edittexttg.setText(post.tgS)
imageView2.setImageResource(post.icon)
if(post.image==0)
imageView3.visibility = View.GONE
else {
imageView3.setImageResource(post.image)
imageView3.visibility = View.VISIBLE
}
ConstraintLayoutImageBorder.setBackgroundResource(
if (post.isBorder) R.drawable.border
else
R.drawable.without_border)
imageButtonLike.setImageResource(if (post.likeByMe) R.drawable.red_heart else R.drawable.heart)
imageButtonLike.setOnClickListener {
listener.onClickLike(post)
}
imageButtonRepost.setOnClickListener {
listener.onClickRepost(post)
}
buttonCancel.setOnClickListener {
listener.cancelEditPost(post,binding)
}
buttonSave.setOnClickListener {
listener.saveEditPost(post,binding)
}
}
}
}
class PostAdapter(
private val listener: Listener
):ListAdapter<Post, PostViewHolder>(PostDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val binding = PostCardBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return PostViewHolder(binding)
}
override fun onBindViewHolder(holder: PostViewHolder, position:Int){
val post = getItem(position)
holder.bind(post, listener)
}
interface Listener{
fun onClickLike(post: Post)
fun onClickRepost(post: Post)
fun onClickMore(post:Post, view: View,binding: PostCardBinding)
fun cancelEditPost(post:Post,binding: PostCardBinding)
fun saveEditPost(post:Post, binding: PostCardBinding)
fun editModeOn(binding: PostCardBinding, content:String)
}
}
fun convertToString(count:Int):String{
return when(count){
in 0..<1_000 -> count.toString()
in 1000..<1_100-> "1K"
in 1_100..<10_000 -> ((count/100).toFloat()/10).toString() + "K"
in 10_000..<1_000_000 -> (count/1_000).toString() + "K"
in 1_000_000..<1_100_000 -> "1M"
in 1_100_000..<10_000_000 -> ((count/100_000).toFloat()/10).toString() + "M"
in 10_000_000..<1_000_000_000 -> (count/1_000_000).toString() + "M"
else -> "ꚙ"
}
} | YP0_01.02/app/src/main/java/ru/btpit/nmedia/PostAdapter.kt | 11445862 |
package ru.btpit.nmedia
import android.app.Application
import android.content.Context
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.semantics.Role.Companion.Image
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.Calendar
import kotlin.random.Random
interface PostRepository {
fun getAll(): LiveData<List<Post>>
fun like(id:Int)
fun repost(id:Int)
fun removeById(id:Int)
fun addPost(post:Post)
fun editById(id:Int, header: String, content: String, url: String)
}
class PostRepositoryInMemoryImpl(context: Context) : PostRepository {
private val gson = Gson()
private val prefs = context.getSharedPreferences("repo", Context.MODE_PRIVATE)
private val type = TypeToken.getParameterized(List::class.java, Post::class.java).type
private val key = "posts"
private var nxtId = 1
//private var posts = emptyList<Post>()
private var posts = listOf(
Post(
1,
"#redraw",
"20 фев в 13:06",
"Приветствуем в нашей группе!\n" +
"Чтобы не потерять доступ к полезному контенту для художников, присоединяйтесь в наш Telegram-канал - ",
"Us telegram",
"Телеграм канал для художников",
999,
999,
7999,
R.mipmap.ic_launcher,
R.drawable.pixel_art
),
Post(
2,
"Анти суши | Суши роллы пицца |",
"Реклама. 0+",
"Вкусные роллы и точка!\n" +
"Напишите нам в группу кодовое сообщение 'подарок' и получите подарок к заказу!",
"Ссылка на секретный канал с подарками",
"АнтиСуши | Суши роллы пицца",
999,
793,
9899,
R.mipmap.ic_sushi,
0,
),
Post(
3,
"Bloom",
"13 минут назад",
"Сохраняет зрительный контакт, пока ест мои цветы",
"",
"",
837,
153,
4599,
R.mipmap.ic_bloom,
R.drawable.cat,
false
),
Post(
4,
"Nature Science",
"вчера в 21:32",
"Вальдшнеп (Scolopax rusticola) — вид птиц семейства бекасовых, гнездящийся в умеренном и субарктическом поясах Евразии.\n" +
"На большей части ареала перелётная птица, ведёт скрытный ночной образ жизни, обычно одиночный, хотя иногда сбивается в небольшие свободные группы.\n" +
"\n" +
"К сожалению, вальдшнеп является объектом спортивной охоты. То есть это не для пропитания, а для развлечения, прикрыв уничтожение птички спортивным интересом.\n" +
"\n" +
"Вальдшнеп - обычно молчаливая птица, за исключением брачного периода, когда во время «тяги» (токования) самец на лету издаёт негромкие благородные подхрюкивания.\n" +
"\n" +
"У вальдшнепов потрясающая покровительственная окраска. Когда он сидит неподвижно, его практически не заметно на лесной подстилке. Летает вальдшнеп медленно.\n" +
"\n" +
"Гнездится в густых лиственных либо смешанных лесах с влажной почвой, часто с густым валежником и подлеском. Отдаёт предпочтение местам вблизи небольших водоёмов с болотистыми берегами для поиска корма и светлыми сухими опушками и перелесками для отдыха.\n" +
"\n" +
"Вальдшнеп – удивительная птица, которая качается при ходьбе. Ее способность качаться связана с адаптацией к болотистой, влажной местности и поиску пищи.\n" +
"\n" +
"Качание вальдшнепа помогает ему сохранять равновесие, избегать проваливания в мягкую почву и более эффективно искать пищу.\n" +
"\n" +
"Вес и скорость движения являются факторами, влияющими на интенсивность качания вальдшнепа.",
"",
"",
4999,
1199,
18999,
R.mipmap.ic_nature,
0,
false,
),
)
init {
prefs.getString(key, null)?.let {
posts = gson.fromJson(it,type)
// data.value = posts
}
}
private fun sync(){
with(prefs.edit()){
putString(key, gson.toJson(posts))
apply()
}
}
private val data = MutableLiveData(posts)
override fun getAll(): LiveData<List<Post>> = data
override fun like(id:Int) {
posts = posts.map {
if (it.id != id) it else
if (it.likeByMe)
it.copy(likeByMe = !it.likeByMe, amountlike = it.amountlike-1)
else
it.copy(likeByMe = !it.likeByMe, amountlike = it.amountlike+1)
}
data.value = posts
sync()
}
override fun repost(id:Int) {
posts = posts.map {
if (it.id != id) it else
if (it.repostByMe)
it.copy(repostByMe = !it.repostByMe, amountRepost = it.amountRepost-1)
else
it.copy(repostByMe = !it.repostByMe, amountRepost = it.amountRepost+1)
}
data.value = posts
sync()
}
override fun removeById(id: Int) {
posts = posts.filter { it.id != id }
data.value = posts
sync()
}
override fun addPost(post: Post) {
posts = listOf(
post.copy(
id = nextId(posts),
publish = Calendar.getInstance().time.toString(),
amountlike = randomNumb(),
amountRepost = randomNumb(),
amountViews = randomNumb(),
)
) + posts
data.value = posts
sync()
}
override fun editById(id: Int,header: String, content: String, url: String) {
posts = posts.map {
if(it.id != id)
it
else {
if (it.id == 0 ) it.id = nextId(posts)
it.copy(author = header, content = content, tgS = url)
}
}
data.value = posts
sync()
}
fun nextId(posts:List<Post>):Int{
var id = 1
posts.forEach{_->
posts.forEach{
if (it.id==id) id=it.id+1
}
}
return id
}
}
class PostViewModel(application: Application) : AndroidViewModel(application) {
private val repository: PostRepository = PostRepositoryInMemoryImpl(application)
private var newPostEmpty = Post(
0,
"Akiva",
"",
"",
"",
"",
0,
0,
0,
R.mipmap.ic_myicon,
0,
false,
)
val data = repository.getAll()
fun like(id:Int) = repository.like(id)
fun repost(id:Int) = repository.repost(id)
fun removeById(id: Int) = repository.removeById(id)
fun addPost(content: String){
newPostEmpty = newPostEmpty.copy(content = content)
repository.addPost(newPostEmpty)
}
fun editById(id: Int,header: String, content: String, url: String) = repository.editById(id, header, content, url)
}
fun randomNumb():Int
{
return when (Random.nextInt(1,4))
{
1,4 -> Random.nextInt(0,1_000)
2 -> Random.nextInt(1_000,1_000_000)
3 -> Random.nextInt(1_000_000,1_000_000_000)
else -> Random.nextInt(0, Int.MAX_VALUE)
}
} | YP0_01.02/app/src/main/java/ru/btpit/nmedia/Repository.kt | 1748342161 |
package ru.btpit.nmedia
import android.graphics.drawable.Drawable
import android.media.Image
import androidx.compose.ui.graphics.ImageBitmap
data class Post (
var id: Int,
val author: String,
val publish: String,
val content: String,
val tgS: String,
val tg: String,
var amountlike: Int,
var amountRepost: Int,
var amountViews: Int,
var icon:Int,
var image: Int,
var isBorder: Boolean = true,
var likeByMe: Boolean = false,
var repostByMe: Boolean = false,
)
| YP0_01.02/app/src/main/java/ru/btpit/nmedia/Post.kt | 984791505 |
package ru.btpit.nmedia
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivityFirst : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_first)
startActivity(Intent(this,MainActivity::class.java))
}
} | YP0_01.02/app/src/main/java/ru/btpit/nmedia/MainActivityFirst.kt | 1478201480 |
package ru.btpit.nmedia
import ru.btpit.nmedia.fragments.HomeFragment
import ru.btpit.nmedia.fragments.ListPostFragment
lateinit var mainActivity: MainActivity
lateinit var listPostFragment: ListPostFragment
lateinit var homeFragment: HomeFragment
| YP0_01.02/app/src/main/java/ru/btpit/nmedia/Constants.kt | 4193800386 |
import org.telegram.telegrambots.meta.TelegramBotsApi
import org.telegram.telegrambots.meta.exceptions.TelegramApiException
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
fun main() {
val bot = TaskBot()
val botsApi = TelegramBotsApi(DefaultBotSession::class.java)
try{
botsApi.registerBot(bot)
} catch (e: TelegramApiException) {
e.printStackTrace()
}
} | task-manager-bot/src/main/kotlin/Main.kt | 663233315 |
import org.telegram.telegrambots.bots.TelegramLongPollingBot
import org.telegram.telegrambots.meta.api.methods.send.SendMessage
import org.telegram.telegrambots.meta.api.objects.Update
import org.telegram.telegrambots.meta.exceptions.TelegramApiException
@Suppress("IMPLICIT_CAST_TO_ANY")
class TaskBot : TelegramLongPollingBot("YOUR_BOT_TOKEN") {
private val tasksToDo: MutableMap<Long, MutableList<String>> = HashMap()
private val tasksDone: MutableMap<Long, MutableList<String>> = HashMap()
override fun getBotUsername(): String {
return "YOUR_BOT_NAME"
}
override fun getBotToken(): String {
return "YOUR_BOT_TOKEN"
}
override fun onUpdateReceived(update: Update){
if (update.hasMessage() && update.message.hasText()) {
val userId = update.message.from.id
val messageText = update.message.text
val chatId = update.message.chatId.toString()
val toDo = tasksToDo[userId]?.mapIndexed { index, s -> "${index + 1}. $s"}?.joinToString("\n") ?: "No tasks today."
val done = tasksDone[userId]?.mapIndexed { index, s -> "${index + 1}. $s"}?.joinToString("\n") ?: "No completed tasks"
val fullMessage = "Active tasks:\n$toDo\n\nDone today: \n$done"
val commands = when{
messageText == "/list" -> {
sendMessage(chatId, fullMessage)
}
messageText.startsWith("/done") -> {
val numbers = messageText.removePrefix("/done")
.trim()
.split("\\s+".toRegex())
.mapNotNull { it.toIntOrNull() }
.sortedDescending() // Sort in reverse order to avoid index shifting
val messagesMarkedDone = mutableListOf<String>()
for (number in numbers) {
val activeMessages = tasksToDo[userId]
if (activeMessages != null && number > 0 && number <= activeMessages.size) {
val doneMessage = activeMessages.removeAt(number - 1)
tasksDone.computeIfAbsent(userId) { mutableListOf() }.add(doneMessage)
messagesMarkedDone.add("Task number $number")
sendMessage(chatId, text = "Completed task is recorded")
} else {
sendMessage(chatId, "Invalid task number: $number")
return // Break out of the loop and method if any number is invalid
}
}
}
messageText == "/clear" -> {
tasksToDo.computeIfAbsent(userId) { mutableListOf() }.clear()
sendMessage(chatId, text = "List restored")
}
messageText == "/start" ->{
sendMessage(chatId, text = "Send any task which you plan to do")
}
else -> tasksToDo.computeIfAbsent(userId) { mutableListOf() }.add(messageText)
}
}
}
private fun sendMessage(chatId: String, text: String) {
val message = SendMessage(chatId, text)
try {
execute(message)
} catch (e: TelegramApiException) {
e.printStackTrace()
}
}
} | task-manager-bot/src/main/kotlin/TaskBot.kt | 105534933 |
package com.raywenderlich.timefighter
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.raywenderlich.timefighter", appContext.packageName)
}
} | Timefighter1/app/src/androidTest/java/com/raywenderlich/timefighter/ExampleInstrumentedTest.kt | 1049911534 |
package com.raywenderlich.timefighter
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)
}
} | Timefighter1/app/src/test/java/com/raywenderlich/timefighter/ExampleUnitTest.kt | 1605137743 |
package com.raywenderlich.timefighter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Timefighter1/app/src/main/java/com/raywenderlich/timefighter/MainActivity.kt | 2073052362 |
package com.example.demo
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DemoApplicationTests {
@Test
fun contextLoads() {
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/demo/DemoApplicationTests.kt | 723354924 |
package com.example.demo
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class Demo2ApplicationTests {
@Test
fun contextLoads() {
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/demo/Demo2ApplicationTests.kt | 365445686 |
package com.example.reserve_local
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class ReserveLocalApplicationTests {
@Test
fun contextLoads() {
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/reserve_local/ReserveLocalApplicationTests.kt | 918828416 |
package crosemont.tdi.g66.restaurantapirest.Controleurs
import com.example.reserve_local.Controlleurs.ReservationControlleur
import com.example.reserve_local.Controlleurs.salleControlleur
import com.example.reserve_local.DAO.SouceDonnées
import com.example.reserve_local.Modele.Reservation
import com.example.reserve_local.Services.ReservationService
import com.example.reserve_local.Services.SalleService
import com.fasterxml.jackson.databind.ObjectMapper
import com.nimbusds.jwt.JWT
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.whenever
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.junit.jupiter.api.Assertions.assertEquals
import java.sql.Time
import org.mockito.Mockito.`when`
import org.springframework.http.ResponseEntity
@SpringBootTest
@ExtendWith(MockitoExtension::class)
class ReservationControleur {
@Mock
lateinit var ReservationService: ReservationService
@InjectMocks
lateinit var ReservationControlleur: ReservationControlleur
@Test
fun `Étant donné obtenirReservationParCode pour une réservation existante`() {
val reservationCode = "ES100"
val expectedReservation = SouceDonnées.Reservations.find { it.CodeReserv == reservationCode }
`when`(ReservationService.chercherParCodeRéservation(reservationCode)).thenReturn(expectedReservation)
val response: ResponseEntity<Reservation> =
ReservationControlleur.obtenirReservationParCode(reservationCode, JWT())
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(expectedReservation, response.body)
}
@Test
fun `Étant donné obtenirReservationParCode pour une réservation non trouvée`() {
val id = "ASD123"
whenever(ReservationService.chercherParCodeRéservation(id)).thenReturn(null)
val response = ReservationControlleur.obtenirReservationParCode(id, JWT())
assertEquals(HttpStatus.NOT_FOUND, response.statusCode)
}
@Test
fun `Test inscrireReservation avec succès`() {
val nouvelleReservation = Reservation(
"ASD123",
Time.valueOf("09:00:00"),
Time.valueOf("13:00:00"),
456,
3,
"new_user_id"
)
`when`(ReservationService.ajouter(nouvelleReservation)).thenReturn(nouvelleReservation)
val response: ResponseEntity<Reservation> =
ReservationControlleur.inscrireReservation(nouvelleReservation, JWT())
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(nouvelleReservation, response.body)
}
// Test pour inscrireReservation qui échoue
@Test
fun `Test inscrireReservation qui échoue`() {
val nouvelleReservation = Reservation(
"ASD123",
Time.valueOf("10:00:00"),
Time.valueOf("14:00:00"),
789,
5,
null
)
`when`(ReservationService.ajouter(nouvelleReservation)).thenReturn(null)
val response: ResponseEntity<Reservation> =
ReservationControlleur.inscrireReservation(nouvelleReservation, JWT())
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.statusCode)
}
// Test pour modifierReservation avec succès
@Test
fun `Test modifierReservation avec succès`() {
val reservationModifiee = Reservation(
"ES100",
Time.valueOf("11:00:00"),
Time.valueOf("15:00:00"),
1011,
2,
"modified_user_id"
)
`when`(ReservationService.modifier(reservationModifiee)).thenReturn(reservationModifiee)
val response: ResponseEntity<Reservation> =
ReservationControlleur.modifierReservation("ES100", reservationModifiee)
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(reservationModifiee, response.body)
}
// Test pour modifierReservation avec une réservation inexistante
@Test
fun `Test modifierReservation avec une réservation inexistante`() {
val reservationInexistante = Reservation(
"ASC123",
Time.valueOf("12:00:00"),
Time.valueOf("16:00:00"),
1314,
1,
"inexisting_user_id"
)
`when`(ReservationService.modifier(reservationInexistante)).thenReturn(reservationInexistante)
val response: ResponseEntity<Reservation> =
ReservationControlleur.modifierReservation("ASC123", reservationInexistante)
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(reservationInexistante, response.body)
}
@Test
fun `Test supprimerReservation pour une réservation existante`() {
val reservationId = "ES100"
val existingReservation = Reservation(
reservationId,
// ... Ajoutez les détails de la réservation existante
)
`when`(reservationService.chercherParCodeRéservation(reservationId)).thenReturn(existingReservation)
val response: ResponseEntity<Any> = reservationController.supprimerReservation(reservationId)
assertEquals(HttpStatus.OK, response.statusCode)
}
@Test
fun `Test supprimerReservation pour une réservation inexistante`() {
val nonExistingReservationId = "ID_INEXISTANT"
`when`(reservationService.chercherParCodeRéservation(nonExistingReservationId)).thenReturn(null)
val response: ResponseEntity<Any> = reservationController.supprimerReservation(nonExistingReservationId)
assertEquals(HttpStatus.NOT_FOUND, response.statusCode)
}
} | API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/reserve_local/Controllers/ReservationControleur.kt | 1391780731 |
package com.example.reserve_local
import com.example.reserve_local.Controlleurs.salleControlleur
import com.example.reserve_local.DAO.SouceDonnées
import com.example.reserve_local.Modele.Salle
import com.example.reserve_local.Services.SalleService
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.whenever
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpStatus
@SpringBootTest
@ExtendWith(MockitoExtension::class)
class SalleControlleurTest {
@Mock
lateinit var salleService: SalleService
@InjectMocks
lateinit var salleControlleur: salleControlleur
@Test
fun `Étant donné obtenirSalle retourne la liste of salles`() {
val expectedSalles = SouceDonnées.Salle
whenever(salleService.chercherTous()).thenReturn(expectedSalles)
val result = salleControlleur.obtenirSalle()
assertEquals(expectedSalles, result)
}
@Test
fun `Étant donné obtenirSalleParId retourne salle pour être valider par id`() {
val id = 5
val expectedSalle = SouceDonnées.Salle.find { it.idSalle== id }
whenever(salleService.chercherParId(id)).thenReturn(expectedSalle)
val response = salleControlleur.obtenirSalleParId(id)
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(expectedSalle, response.body)
}
@Test
fun `Étant donné obtenirSalleParId retourne pas trouver pour cet id`() {
val id = 99
whenever(salleService.chercherParId(id)).thenReturn(null)
val response = salleControlleur.obtenirSalleParId(id)
assertEquals(HttpStatus.NOT_FOUND, response.statusCode)
}
@Test
fun `Étant donné inscrireSalle renvoie la salle lorsque l'ajout est réussi`() {
val nouvelleSalle = Salle(3, "B207", "Windows", "10:00", "19:00", "salle3", 3)
`when`(salleService.ajouter(nouvelleSalle)).thenReturn(nouvelleSalle)
val réponse = salleControlleur.inscrireSalle(nouvelleSalle)
assertEquals(HttpStatus.OK, réponse.statusCode)
assertEquals(nouvelleSalle, réponse.body)
}
@Test
fun `Étant donné inscrireSalle renvoie une erreur serveur interne lorsque l'ajout échoue`() {
val nouvelleSalle = Salle(3, "B207", "Windows", "10:00", "19:00", "salle3", 3)
`when`(salleService.ajouter(nouvelleSalle)).thenReturn(null)
val réponse = salleControlleur.inscrireSalle(nouvelleSalle)
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, réponse.statusCode)
}
@Test
fun `Étant donné modifierSalle renvoie la salle mise à jour`() {
val salleMiseAJour = Salle(1, "B205", "Windows", "10:00", "20:00", "salle2", 1)
`when`(salleService.modifier(salleMiseAJour)).thenReturn(salleMiseAJour)
val réponse = salleControlleur.modifierSalle(salleMiseAJour)
assertEquals(HttpStatus.OK, réponse.statusCode)
assertEquals(salleMiseAJour, réponse.body)
}
@Test
fun `Étant donné modifierSalle renvoie non trouvé pour une salle inexistante`() {
val salleInexistante = Salle(99, "Inexistante", "None", "00:00", "00:00", "none", 0)
`when`(salleService.modifier(salleInexistante)).thenReturn(null)
val réponse = salleControlleur.modifierSalle(salleInexistante)
assertEquals(HttpStatus.NOT_FOUND, réponse.statusCode)
}
@Test
fun `Étant donné supprimerSalle renvoie OK pour une salle existante`() {
val id = 1
val salleExistante = Salle(id, "B205", "Windows", "10:00", "19:00", "salle2", 1)
`when`(salleService.chercherParId(id)).thenReturn(salleExistante)
val réponse = salleControlleur.supprimerSalle(id)
assertEquals(HttpStatus.OK, réponse.statusCode)
}
@Test
fun `Étant donné supprimerSalle renvoie non trouvé pour une salle inexistante`() {
val id = 99
`when`(salleService.chercherParId(id)).thenReturn(null)
val réponse = salleControlleur.supprimerSalle(id)
assertEquals(HttpStatus.NOT_FOUND, réponse.statusCode)
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/reserve_local/Controllers/SalleControlleurTest.kt | 3552472686 |
package com.example.reserve_local
import com.example.reserve_local.Controlleurs.salleControlleur
import com.example.reserve_local.DAO.SouceDonnées
import com.example.reserve_local.Modele.Salle
import com.example.reserve_local.Services.SalleService
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.whenever
import org.springframework.http.HttpStatus
@ExtendWith(MockitoExtension::class)
class SalleControlleurTest {
@Mock
lateinit var salleService: SalleService
@InjectMocks
lateinit var salleControlleur: salleControlleur
@Test
fun `obtenirSalle retourne la liste of salles`() {
val expectedSalles = SouceDonnées.Salle
whenever(salleService.chercherTous()).thenReturn(expectedSalles)
val result = salleControlleur.obtenirSalle()
assertEquals(expectedSalles, result)
}
@Test
fun `obtenirSalleParId retourne salle pour être valider par id`() {
val id = 5
val expectedSalle = SouceDonnées.Salle.find { it.idSalle== id }
whenever(salleService.chercherParId(id)).thenReturn(expectedSalle)
val response = salleControlleur.obtenirSalleParId(id)
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals(expectedSalle, response.body)
}
@Test
fun `obtenirSalleParId retourne pas trouver pour cet id`() {
val id = 99
whenever(salleService.chercherParId(id)).thenReturn(null)
val response = salleControlleur.obtenirSalleParId(id)
assertEquals(HttpStatus.NOT_FOUND, response.statusCode)
}
@Test
fun `inscrireSalle renvoie la salle lorsque l'ajout est réussi`() {
val nouvelleSalle = Salle(3, "B207", "Windows", "10:00", "19:00", "salle3", 3)
`when`(salleService.ajouter(nouvelleSalle)).thenReturn(nouvelleSalle)
val réponse = salleControlleur.inscrireSalle(nouvelleSalle)
assertEquals(HttpStatus.OK, réponse.statusCode)
assertEquals(nouvelleSalle, réponse.body)
}
@Test
fun `inscrireSalle renvoie une erreur serveur interne lorsque l'ajout échoue`() {
val nouvelleSalle = Salle(3, "B207", "Windows", "10:00", "19:00", "salle3", 3)
`when`(salleService.ajouter(nouvelleSalle)).thenReturn(null)
val réponse = salleControlleur.inscrireSalle(nouvelleSalle)
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, réponse.statusCode)
}
@Test
fun `modifierSalle renvoie la salle mise à jour`() {
val salleMiseAJour = Salle(1, "B205", "Windows", "10:00", "20:00", "salle2", 1)
`when`(salleService.modifier(salleMiseAJour)).thenReturn(salleMiseAJour)
val réponse = salleControlleur.modifierSalle(salleMiseAJour)
assertEquals(HttpStatus.OK, réponse.statusCode)
assertEquals(salleMiseAJour, réponse.body)
}
@Test
fun `modifierSalle renvoie non trouvé pour une salle inexistante`() {
val salleInexistante = Salle(99, "Inexistante", "None", "00:00", "00:00", "none", 0)
`when`(salleService.modifier(salleInexistante)).thenReturn(null)
val réponse = salleControlleur.modifierSalle(salleInexistante)
assertEquals(HttpStatus.NOT_FOUND, réponse.statusCode)
}
@Test
fun `supprimerSalle renvoie OK pour une salle existante`() {
val id = 1
val salleExistante = Salle(id, "B205", "Windows", "10:00", "19:00", "salle2", 1)
`when`(salleService.chercherParId(id)).thenReturn(salleExistante)
val réponse = salleControlleur.supprimerSalle(id)
assertEquals(HttpStatus.OK, réponse.statusCode)
}
@Test
fun `supprimerSalle renvoie non trouvé pour une salle inexistante`() {
val id = 99
`when`(salleService.chercherParId(id)).thenReturn(null)
val réponse = salleControlleur.supprimerSalle(id)
assertEquals(HttpStatus.NOT_FOUND, réponse.statusCode)
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/reserve_local/SalleControlleurTest.kt | 4009104534 |
package com.example.reserve_local
import com.example.reserve_local.DAO.SouceDonnées
import com.example.reserve_local.Modele.Salle
import com.example.reserve_local.Services.SalleService
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.test.context.event.annotation.BeforeTestMethod
import java.sql.Time
import org.springframework.web.bind.annotation.*
class TestMethod (val service : SalleService){
private lateinit var sourceDonnées: SouceDonnées
@BeforeTestMethod
fun setUp() {
sourceDonnées = SouceDonnées()
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/reserve_local/TestMethod.kt | 4118439443 |
package com.example.demoiapi
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DemoiapiApplicationTests {
@Test
fun contextLoads() {
}
}
| API-Reservation-de-locaux/Reserve_local/src/test/kotlin/com/example/demoiapi/DemoiapiApplicationTests.kt | 141915487 |
package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/demo/DemoApplication.kt | 388720869 |
package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Demo2Application
fun main(args: Array<String>) {
runApplication<Demo2Application>(*args)
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/demo/Demo2Application.kt | 2704074702 |
package com.example.reserve_local
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ReserveLocalApplication
fun main(args: Array<String>) {
runApplication<ReserveLocalApplication>(*args)
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/ReserveLocalApplication.kt | 806056508 |
package com.example.reserve_local.GestionAcces
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator
import org.springframework.security.oauth2.core.OAuth2TokenValidator
import org.springframework.security.oauth2.jwt.*
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.config.annotation.web.invoke
import org.springframework.security.oauth2.jwt.JwtValidators
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
@Configuration
@EnableWebSecurity
class Securitéconfig {
@Value("\${auth0.audience}")
private val audience: String = String()
@Value("\${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private val issuer: String = String()
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize("/", permitAll)
authorize(HttpMethod.GET, "/**", permitAll)
authorize(HttpMethod.PUT, "/Reservations/**", hasAuthority("PERMISSION_write"))
authorize(HttpMethod.DELETE, "/Salles/**", hasAuthority("PERMISSION_delete"))
authorize(HttpMethod.PUT, "/Salles/**", hasAuthority("PERMISSION_write"))
authorize(HttpMethod.POST, "/Salles", hasAuthority("PERMISSION_create"))
// authorize(HttpMethod.GET, "/Reservations", authenticated)
//authorize(HttpMethod.POST, "/**", authenticated)
//authorize(HttpMethod.PUT, "/**", authenticated)
//authorize(HttpMethod.DELETE, "/**", authenticated)
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt { }
}
}
return http.build()
}
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
val jwtGrantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("permissions")
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("PERMISSION_")
val jwtAuthenticationConverter = JwtAuthenticationConverter()
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter)
jwtAuthenticationConverter.setPrincipalClaimName("sub")
return jwtAuthenticationConverter
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwtDecoder = JwtDecoders.fromOidcIssuerLocation(issuer) as NimbusJwtDecoder
val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidateur(audience)
val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuer)
val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
jwtDecoder.setJwtValidator(withAudience)
return jwtDecoder
}
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/GestionAcces/Securitéconfig.kt | 1777065071 |
package com.example.reserve_local.GestionAcces
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties
import org.springframework.security.oauth2.core.OAuth2Error
import org.springframework.security.oauth2.core.OAuth2TokenValidator
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult
import org.springframework.security.oauth2.jwt.Jwt
class AudienceValidateur(private val audience: String) : OAuth2TokenValidator<Jwt> {
override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
val error = OAuth2Error("invalide_jeton", "Il manque l'audience requise", null)
return if (jwt.audience.contains(audience)) {
OAuth2TokenValidatorResult.success()
} else OAuth2TokenValidatorResult.failure(error)
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/GestionAcces/AudienceValidateur.kt | 1295389977 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Reservation
interface DAO<T> {
fun chercherTous(): List<T>
fun chercherParCode(code: String): T?
fun ajouter(element: T): T?
fun modifier(element: T): T?
fun supprimer(element: T): T?
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/DAO.kt | 1056909747 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Salle
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Repository
@Repository
class SalleDAOImpl(val db: JdbcTemplate, private val jdbcTemplate: JdbcTemplate) : SalleDAO{
override fun chercherTous(): List<Salle> {
val sql = "SELECT * FROM Salle"
return db.query(sql) { rs, _ ->
Salle(
idSalle = rs.getInt("idSalle"),
nombrePersonnes = rs.getInt("nombrePersonnes"),
heureOuverture = rs.getString("heureOuverture"),
heureFermeture = rs.getString("heureFermeture"),
nomSalle = rs.getString("nomSalle"),
imageSalle = rs.getString("imageSalle"),
equipement = rs.getString("Equipement")
)
/*
val idSalle: Int,
val nombrePersonnes: Int,
val nomSalle: String,
val heureOuverture: String,
val heureFermeture: String,
val Equipement: String,
val imageSalle: String
)
*/
}
}
override fun chercherParId(id: Int): Salle? {
val sql = "SELECT * FROM Salle WHERE idSalle = ?"
return db.queryForObject(sql, { rs, _ ->
Salle(
idSalle = rs.getInt("idSalle"),
nombrePersonnes = rs.getInt("nombrePersonnes"),
heureOuverture = rs.getString("heureOuverture"),
heureFermeture = rs.getString("heureFermeture"),
nomSalle = rs.getString("nomSalle"),
imageSalle = rs.getString("imageSalle"),
equipement = rs.getString("Equipement")
)
}, id)
}
override fun chercherParCode(code: String): Salle? {
TODO("Not yet implemented")
}
override fun ajouter(element: Salle): Salle? {
TODO("Not yet implemented")
}
override fun ajouterSalle(salle: Salle): Salle {
val sql = "INSERT INTO Salle (IdSalle, nombrePersonnes, heureOuverture, heureFermeture, nomSalle, imageSalle, Equipement) VALUES (?, ?, ?, ?, ?, ?, ?)"
jdbcTemplate.update(sql, salle.idSalle, salle.nombrePersonnes, salle.heureOuverture, salle.heureFermeture, salle.nomSalle, salle.imageSalle, salle.equipement)
return salle
}
override fun modifier(salle: Salle): Salle? {
val sql = """
UPDATE Salle
SET nombrePersonnes = ?,
nomSalle = ?,
heureOuverture = ?,
heureFermeture = ?,
Equipement = ?,
imageSalle = ?
WHERE IdSalle = ?
"""
val updated = db.update(sql,
salle.nombrePersonnes,
salle.nomSalle,
salle.heureOuverture,
salle.heureFermeture,
salle.equipement,
salle.imageSalle,
salle.idSalle)
return if (updated > 0) salle else null
}
override fun supprimer(salle: Salle): Salle? {
// Supprimez d'abord les réservations liées
val sqlDeleteReservations = "DELETE FROM Reservation WHERE IdSalle = ?"
db.update(sqlDeleteReservations, salle.idSalle)
// Ensuite, supprimez la salle
val sqlDeleteSalle = "DELETE FROM Salle WHERE IdSalle = ?"
val updated = db.update(sqlDeleteSalle, salle.idSalle)
return if (updated > 0) salle else null
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/SalleDAOImpl.kt | 1813430416 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Reservation
import com.example.reserve_local.Modele.Salle
import org.springframework.stereotype.Component
import java.sql.Time
@Component
class SouceDonnées {
companion object{
val Reservations = mutableListOf(
Reservation("ES100", Time.valueOf("10:00:00"), Time.valueOf("12:00:00"), 1, 15, "656d0dba34408e731c39de12"),
Reservation ("RES100", Time.valueOf("10:00:00"), Time.valueOf("15:00:00"), 6, 3, "auth0|656d0dba34408e731c39de12"),
Reservation ("RES101", Time.valueOf("10:00:00"), Time.valueOf("11:00:00"), 5, 2, "auth0|656d0dba34408e731c39de12"),
)
/*
val Salles = mutableListOf(
// Salle(1, 4, Time.valueOf("09:00:00"), Time.valueOf("11:00:00"), 1)
)
*/
val Salle = mutableListOf(
Salle (5,4,"8:00","10:00","B205","salle2","Windows"),
Salle (6,4,"8:00","10:00","B305","salle2","Windows")
)
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/SouceDonnées.kt | 990175018 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Salle
import org.springframework.stereotype.Repository
@Repository
interface SalleDAO : DAO<Salle> {
override fun chercherTous(): List<Salle>
fun chercherParId(id: Int): Salle?
fun ajouterSalle(salle: Salle): Salle
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/SalleDAO.kt | 2354124234 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Reservation
import org.springframework.stereotype.Repository
@Repository
interface ReservationDAO : DAO<Reservation> {
override fun chercherTous(): List<Reservation>
fun chercherParCodeRéservation(CodeRéservation: String): Reservation?
fun getReservationsByUserId(userId: String): List<Reservation>
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/ReservationDAO.kt | 1402831617 |
package com.example.reserve_local.DAO
import com.example.reserve_local.Modele.Reservation
import org.springframework.jdbc.core.BeanPropertyRowMapper
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Repository
@Repository
class ReservationDAOImpl(val db: JdbcTemplate) : ReservationDAO {
override fun chercherTous(): List<Reservation> {
val sql = "SELECT * FROM Reservation"
return db.query(sql) { rs, _ ->
Reservation(
CodeReserv = rs.getString("CodeReserv"),
HArrive = rs.getTime("HArrive"),
Hdepart = rs.getTime("Hdepart"),
IdSalle = rs.getInt("IdSalle"),
NbrPersonnes = rs.getInt("NbrPersonnes"),
IdUtilisateur = rs.getString("IdUtilisateur")
)
}
}
override fun chercherParCodeRéservation(CodeRéservation: String): Reservation? {
val sql = "SELECT * FROM Reservation WHERE CodeReserv = ?"
return db.queryForObject(sql, { rs, _ ->
Reservation(
CodeReserv = rs.getString("CodeReserv"),
HArrive = rs.getTime("HArrive"),
Hdepart = rs.getTime("Hdepart"),
IdSalle = rs.getInt("IdSalle"),
NbrPersonnes = rs.getInt("NbrPersonnes"),
IdUtilisateur = rs.getString("IdUtilisateur")
)
}, CodeRéservation)
}
override fun getReservationsByUserId(userId: String): List<Reservation> {
val sql = "SELECT * FROM Reservation WHERE IdUtilisateur = ?"
return db.query(sql, { rs, _ ->
Reservation(
CodeReserv = rs.getString("CodeReserv"),
HArrive = rs.getTime("HArrive"),
Hdepart = rs.getTime("Hdepart"),
IdSalle = rs.getInt("IdSalle"),
NbrPersonnes = rs.getInt("NbrPersonnes"),
IdUtilisateur = rs.getString("IdUtilisateur")
)
}, userId)
}
override fun chercherParCode(code: String): Reservation? = SouceDonnées.Reservations.find { it.CodeReserv==code }
override fun ajouter(reservation: Reservation): Reservation? {
val sql = "INSERT INTO Reservation (CodeReserv, HArrive, Hdepart, IdSalle, NbrPersonnes, IdUtilisateur) VALUES (?, ?, ?, ?, ?, ?)"
db.update(sql, reservation.CodeReserv, reservation.HArrive, reservation.Hdepart, reservation.IdSalle, reservation.NbrPersonnes, reservation.IdUtilisateur)
return reservation
}
override fun modifier(reservation: Reservation): Reservation? {
val sql = "UPDATE Reservation SET HArrive = ?, Hdepart = ?, IdSalle = ?, NbrPersonnes = ?, IdUtilisateur = ? WHERE CodeReserv = ?"
val updated = db.update(sql, reservation.HArrive, reservation.Hdepart, reservation.IdSalle, reservation.NbrPersonnes, reservation.IdUtilisateur, reservation.CodeReserv)
return if (updated > 0) reservation else null
}
override fun supprimer(reservation: Reservation): Reservation? {
val sql = "DELETE FROM Reservation WHERE CodeReserv = ?"
val deleted = db.update(sql, reservation.CodeReserv)
return if (deleted > 0) reservation else null
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/DAO/ReservationDAOImpl.kt | 1992645850 |
package crosemont.tdi.g66.restaurantapirest.Exceptions
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
@ResponseStatus(HttpStatus.NOT_FOUND)
class RessourceInexistanteException(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause) {
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Exceptions/RessourceInexistanteException.kt | 2358293825 |
package crosemont.tdi.g66.restaurantapirest.Controleurs
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.security.Principal
@RestController
class APIControleur {
@GetMapping("/")
fun index() = "Service de réservation"
@GetMapping("/jeton")
fun getPrincipalInfo(principal: JwtAuthenticationToken): Map<String, Any> {
val authorities: Collection<String> = principal.authorities
.stream()
.map { obj: GrantedAuthority -> obj.authority }
.toList()
val info: MutableMap<String, Any> = HashMap()
info["name"] = principal.name
info["authorities"] = authorities
info["tokenAttributes"] = principal.tokenAttributes
return info
}
@GetMapping("/utilisateur")
fun lireUtilisateur(principal: Principal?): String? {
if (principal != null) {
return "Bonjour, " + principal.name
} else {
return null
}
}
@GetMapping("/etudiant")
@PreAuthorize("hasAuthority('ROLE_ETUDIANT')")
fun getDataPourEtudiant(): ResponseEntity<Any> {
val dataEtudiant = mapOf("message" to "Données réservées à l'étudiant")
return ResponseEntity.ok(dataEtudiant)
}
@GetMapping("/admin")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
fun getDataPourAdmin(): ResponseEntity<Any> {
val dataAdmin = mapOf("message" to "Données réservées à l'administrateur")
return ResponseEntity.ok(dataAdmin)
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Controlleurs/APIControleur.kt | 4077456736 |
package com.example.reserve_local.Controlleurs
import com.example.reserve_local.Modele.Reservation
import com.example.reserve_local.Services.ReservationService
import io.swagger.v3.oas.annotations.Operation
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.jwt.Jwt
@RestController
@RequestMapping("\${api.base-path:}")
@Tag(
name = "Reservation",
description = "Points d'accès aux ressources liées aux reservations inscrits au service."
)
class ReservationControlleur (val service: ReservationService){
@Operation(summary = "Obtenir la liste des réservations de l'utilisateur actuel")
@GetMapping("/Reservations")
fun getReservationsForCurrentUser(@AuthenticationPrincipal jwt: Jwt): ResponseEntity<*> {
val userIdString = jwt.getClaimAsString("sub")
val admin = jwt.getClaimAsString("permissions")
if (userIdString != null) {
val userIdInt = userIdString.toString()
val reservations = if (admin?.contains("administrator") == true) {
service.chercherTous()
} else {
service.getReservationsByUserId(userIdInt)
}
return ResponseEntity.ok(reservations)
} else {
val errorMessage = "ID de l'utilisateur invalide: $userIdString"
val errorResponse = mapOf("error" to errorMessage)
return ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST)
}
}
@ApiResponses(value = [
ApiResponse(responseCode = "200", description = "Reservation trouvé"),
ApiResponse(responseCode = "404", description = "Reservation inexistant")
])
@GetMapping("/Reservations/{Code_reservation}")
fun obtenirReservationParCode(@PathVariable Code_reservation: String, @AuthenticationPrincipal jwt: Jwt): ResponseEntity<Reservation> {
val userIdString = jwt.getClaimAsString("sub")
val admin = jwt.getClaimAsString("permissions")
if (userIdString != null) {
val reservation = service.chercherParCodeRéservation(Code_reservation)
if (reservation != null) {
if (admin?.contains("administrator") == true || reservation.IdUtilisateur == userIdString) {
return ResponseEntity.ok(reservation)
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
} else {
return ResponseEntity.badRequest().build()
}
} else {
return ResponseEntity.notFound().build()
}
}
@PostMapping("/Reservations")
fun inscrireReservation(@RequestBody reservation: Reservation, @AuthenticationPrincipal jwt: Jwt): ResponseEntity<Reservation> {
val userIdString = jwt.getClaimAsString("sub")
val admin = jwt.getClaimAsString("permissions")
if (admin?.contains("administrator") == true) {
val added = service.ajouter(reservation)
return ResponseEntity.ok(added)
} else {
reservation.IdUtilisateur = userIdString
val added = service.ajouter(reservation)
return ResponseEntity.ok(added)
}
}
@PutMapping("/Reservations/{Code_reservation}")
fun modifierReservation(@PathVariable Code_reservation: String, @RequestBody reservation: Reservation): ResponseEntity<Reservation> {
if (reservation.CodeReserv != Code_reservation) {
return ResponseEntity.badRequest().build()
}
val updated = service.modifier(reservation)
return if (updated != null) ResponseEntity.ok(updated) else ResponseEntity(HttpStatus.NOT_FOUND)
}
@DeleteMapping("/Reservations/{CodeReserv}")
fun supprimerReservation(@PathVariable CodeReserv: String, @AuthenticationPrincipal jwt: Jwt): ResponseEntity<Any> {
val userIdString = jwt.getClaimAsString("sub")
val permissions = jwt.getClaimAsString("permissions")
val reservation = service.chercherParCodeRéservation(CodeReserv)
if (reservation != null) {
if (permissions?.contains("delete") == true || reservation.IdUtilisateur == userIdString) {
service.supprimer(reservation)
val Message = "La reservation a ete supprimer avec succees"
val Response = mapOf("Confirmation:" to Message)
return ResponseEntity(Response,HttpStatus.OK)
} else {
val errorMessage = "Cette réservation n'appartient pas à vous"
val errorResponse = mapOf("error" to errorMessage)
return ResponseEntity(errorResponse,HttpStatus.UNAUTHORIZED)
}
}
return ResponseEntity(HttpStatus.NOT_FOUND)
}
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Controlleurs/ReservationControlleur.kt | 2545586188 |
package com.example.reserve_local.Controlleurs
import com.example.reserve_local.Modele.Reservation
import com.example.reserve_local.Modele.Salle
import com.example.reserve_local.Services.SalleService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class salleControlleur (val service : SalleService){
@GetMapping("/Salles")
fun obtenirSalle() = service.chercherTous()
@GetMapping("/Salles/{id_salle}")
fun obtenirSalleParId(@PathVariable id_salle: Int): ResponseEntity<Salle> =
service.chercherParId(id_salle)?.let { ResponseEntity.ok(it) }
?: ResponseEntity(HttpStatus.NOT_FOUND)
@PostMapping("/Salles")
fun ajouterSalle(@RequestBody salle: Salle): ResponseEntity<Salle> {
val nouvelleSalle = service.ajouterSalle(salle)
return ResponseEntity(nouvelleSalle, HttpStatus.CREATED)
}
@PutMapping("/Salles/{id_salle}")
fun modifierSalle(@PathVariable id_salle: Int, @RequestBody salle: Salle): ResponseEntity<Salle> {
if (salle.idSalle != id_salle) {
return ResponseEntity.badRequest().build() // ID incohérent
}
return service.modifier(salle)?.let { ResponseEntity.ok(it) }
?: ResponseEntity(HttpStatus.NOT_FOUND)
}
@DeleteMapping("/Salles/{id_salle}")
fun supprimerSalle(@PathVariable id_salle: Int): ResponseEntity<Any> =
service.chercherParId(id_salle)?.let {
service.supprimer(it)
ResponseEntity(HttpStatus.OK)
} ?: ResponseEntity(HttpStatus.NOT_FOUND)
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Controlleurs/salleControlleur.kt | 228488302 |
package com.example.reserve_local
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SpringDocConfiguration {
@Bean
fun apiInfo(): OpenAPI {
return OpenAPI()
.info(
Info()
.title("API du service de gestion des reservation")
.description("API du service de gestion des reservation")
.version("1.0.0")
)
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/SpringDocConfiguration.kt | 3689888012 |
package com.example.reserve_local.Services
import com.example.reserve_local.DAO.ReservationDAO
import com.example.reserve_local.Modele.Reservation
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
class ReservationService (@Qualifier("reservationDAOImpl") val dao: ReservationDAO) {
fun chercherTous() : List<Reservation> = dao.chercherTous()
fun chercherParCodeRéservation(CodeRéservation: String):Reservation? = dao.chercherParCodeRéservation(CodeRéservation)
fun ajouter(reservation: Reservation): Reservation? = dao.ajouter(reservation)
fun modifier(reservation: Reservation):Reservation? = dao.modifier(reservation)
fun supprimer(reservation: Reservation): Reservation? = dao.supprimer(reservation)
fun getReservationsByUserId(userId: String): List<Reservation> {
return dao.getReservationsByUserId(userId)
}
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Services/ReservationService.kt | 3242495048 |
package com.example.reserve_local.Services
import com.example.reserve_local.DAO.SalleDAO
import com.example.reserve_local.Modele.Reservation
import com.example.reserve_local.Modele.Salle
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
class SalleService (@Qualifier("salleDAOImpl") val dao: SalleDAO){
fun chercherTous(): List<Salle> = dao.chercherTous()
fun chercherParId(id:Int): Salle? = dao.chercherParId(id)
fun ajouterSalle(salle: Salle): Salle {
return dao.ajouterSalle(salle)
}
fun modifier(salle: Salle) = dao.modifier(salle)?.let { it }
fun supprimer(salle: Salle): Salle? = dao.supprimer(salle)
fun chercherParCode(code: String): Salle? = dao.chercherParCode(code)
} | API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Services/SalleService.kt | 2883856584 |
package com.example.reserve_local.Modele
import java.sql.Time
class Salle(
val idSalle: Int,
val nombrePersonnes: Int,
val heureOuverture: String,
val heureFermeture: String,
val nomSalle: String,
val imageSalle: String,
val equipement: String
)
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Modele/Salle.kt | 1323719130 |
package com.example.reserve_local.Modele
import java.sql.Time
class Reservation(
val CodeReserv: String,
val HArrive: Time,
val Hdepart: Time,
val IdSalle: Int,
val NbrPersonnes: Int,
var IdUtilisateur: String?
)
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/reserve_local/Modele/Reservation.kt | 1453432415 |
package com.example.demoiapi
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DemoiapiApplication
fun main(args: Array<String>) {
runApplication<DemoiapiApplication>(*args)
}
| API-Reservation-de-locaux/Reserve_local/src/main/kotlin/com/example/demoiapi/DemoiapiApplication.kt | 4079678543 |
package lojas.longo.lojaslongoestoque
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class LojasLongoEstoqueApplicationTests {
@Test
fun contextLoads() {
}
}
| ApiGestaoProdutosUsuarios/src/test/kotlin/api/cleancode/api/LojasLongoEstoqueApplicationTests.kt | 1899247359 |
package lojas.longo.lojaslongoestoque.core.entity
data class Product(val id: Long?, val name:String, val size: String, val brand: String, val color:String, val gender:String)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/core/entity/Product.kt | 1552088348 |
// Pacote da Camada de Domínio - Entidade
package lojas.longo.lojaslongoestoque.core.entity
data class User(val id: Long?, val username: String, val password: String)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/core/entity/User.kt | 1351155456 |
package lojas.longo.lojaslongoestoque.core
import lojas.longo.lojaslongoestoque.core.entity.Product
interface ProductGateway {
fun save(product: Product): Product
fun findById(id: Long): Product?
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/core/ProductGateway.kt | 3116157800 |
// Pacote da Camada de Domínio - Interface de Repositório
package lojas.longo.lojaslongoestoque.core
import lojas.longo.lojaslongoestoque.core.entity.User
interface UserGateway {
fun save(user: User): User
fun findById(id: Long): User?
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/core/UserGateway.kt | 2936657873 |
// Pacote da Camada de Configuração
package lojas.longo.lojaslongoestoque.config
import lojas.longo.lojaslongoestoque.adapters.gateway.UserGatewayImpl
import lojas.longo.lojaslongoestoque.adapters.gateway.UserRepository
import lojas.longo.lojaslongoestoque.adapters.impl.CreateUserUseCaseImpl
import lojas.longo.lojaslongoestoque.application.usecases.CreateUserUseCase
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class AppConfig(private val userRepository: UserRepository) {
@Bean
fun createUserUseCase(): CreateUserUseCase {
return CreateUserUseCaseImpl(UserGatewayImpl(userRepository))
}
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/config/AppConfig.kt | 1807463524 |
package lojas.longo.lojaslongoestoque.adapters.impl
import lojas.longo.lojaslongoestoque.application.usecases.FindUserByIdUseCase
import lojas.longo.lojaslongoestoque.core.UserGateway
import lojas.longo.lojaslongoestoque.core.entity.User
import org.springframework.stereotype.Service
@Service
class FindUserByIdUseCaseImpl(private val userGateway: UserGateway) : FindUserByIdUseCase {
override fun execute(id: Long): User? {
return userGateway.findById(id)
}
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/impl/FindUserByIdUseCaseImpl.kt | 1672741311 |
package lojas.longo.lojaslongoestoque.adapters.impl
import lojas.longo.lojaslongoestoque.application.usecases.CreateProductUseCase
import lojas.longo.lojaslongoestoque.core.ProductGateway
import lojas.longo.lojaslongoestoque.core.entity.Product
import org.springframework.stereotype.Service
@Service
class CreateProductUseCaseImpl(private val productGateway: ProductGateway) : CreateProductUseCase {
override fun execute(name:String, size: String, brand: String, color:String, gender:String) : Product{
// Lógica de negócios para criação de produto
val newProduct = Product(null,name,size,brand,color,gender)
return productGateway.save(newProduct)
}
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/impl/CreateProductUseCaseImpl.kt | 835988696 |
// Pacote da Camada de Adaptadores - Implementação do Caso de Uso
package lojas.longo.lojaslongoestoque.adapters.impl
import lojas.longo.lojaslongoestoque.application.usecases.CreateUserUseCase
import lojas.longo.lojaslongoestoque.core.UserGateway
import lojas.longo.lojaslongoestoque.core.entity.User
import org.springframework.stereotype.Service
@Service
class CreateUserUseCaseImpl(private val userGateway: UserGateway) : CreateUserUseCase {
override fun execute(username: String, password: String): User {
// Lógica de negócios para criação de usuário
val newUser = User(null,username, password)
return userGateway.save(newUser)
}
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/impl/CreateUserUseCaseImpl.kt | 3677503718 |
package lojas.longo.lojaslongoestoque.adapters.impl
import lojas.longo.lojaslongoestoque.application.usecases.FindProductByIdUseCase
import lojas.longo.lojaslongoestoque.core.ProductGateway
import lojas.longo.lojaslongoestoque.core.entity.Product
import org.springframework.stereotype.Service
@Service
class FindProductByIdUseCaseImpl(private val productGateway: ProductGateway): FindProductByIdUseCase {
override fun exeecute(id: Long): Product? {
return productGateway.findById(id)
}
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/impl/FindProductByIdUseCaseImpl.kt | 491522819 |
// Pacote da Camada de Adaptadores - Implementação do Gateway
package lojas.longo.lojaslongoestoque.adapters.gateway
import lojas.longo.lojaslongoestoque.core.UserGateway
import lojas.longo.lojaslongoestoque.core.entity.User
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
interface UserRepository : CrudRepository<UserEntity, Long>
@Service
class UserGatewayImpl(private val userRepository: UserRepository) : UserGateway {
override fun save(user: User): User {
// Lógica de persistência aqui
val entity = UserEntity(null,user.username,user.password)
val savedEntity = userRepository.save(entity)
return User(savedEntity.id, savedEntity.username, savedEntity.password)
}
override fun findById(id: Long): User {
// Lógica de busca por ID
val optionalEntity = userRepository.findById(id)
return if (optionalEntity.isPresent) {
val entity = optionalEntity.get()
User(entity.id, entity.username, entity.password)
} else {
throw error("Error")
}
}
// Implemente outros métodos conforme necessário
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/gateway/UserRepository.kt | 1595654657 |
package lojas.longo.lojaslongoestoque.adapters.gateway
import jakarta.persistence.*
import org.springframework.data.relational.core.mapping.Column
@Entity
@Table(name = "Products")
data class ProductEntity(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long?,
@Column
val name:String,
@Column
val size: String,
@Column
val brand: String,
@Column
val color:String,
@Column
val gender:String)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/gateway/ProductEntity.kt | 161666767 |
package lojas.longo.lojaslongoestoque.adapters.gateway
import lojas.longo.lojaslongoestoque.core.ProductGateway
import lojas.longo.lojaslongoestoque.core.entity.Product
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
interface ProductRepository : CrudRepository <ProductEntity, Long>
@Service
class ProductGatewayImpl (private val productRepository: ProductRepository) : ProductGateway{
override fun save(product: Product): Product {
// Lógica de persistência aqui
val entity = ProductEntity(null, product.name, product.size, product.brand, product.color, product.gender)
val savedEntity = productRepository.save(entity)
return Product(savedEntity.id, savedEntity.name, savedEntity.size, savedEntity.brand, savedEntity.color, savedEntity.gender)
}
override fun findById(id: Long): Product {
// Lógica de busca por ID
val optionalEntity = productRepository.findById(id)
return if (optionalEntity.isPresent) {
val entity = optionalEntity.get()
Product(entity.id, entity.name, entity.size, entity.brand, entity.color, entity.color)
}else{
throw error("Error")
}
}
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/gateway/ProductRepository.kt | 560272296 |
// Pacote da Camada de Adaptadores - Entidade JPA
package lojas.longo.lojaslongoestoque.adapters.gateway
import jakarta.persistence.*
@Entity
@Table(name = "Users")
data class UserEntity(
@Id@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long?,
@Column
val username: String,
@Column
val password: String
)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/adapters/gateway/UserEntity.kt | 646429782 |
package lojas.longo.lojaslongoestoque
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class LojasLongoEstoqueApplication
fun main(args: Array<String>) {
runApplication<LojasLongoEstoqueApplication>(*args)
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/ApplicationMain.kt | 4240442384 |
package lojas.longo.lojaslongoestoque.application.controller
import lojas.longo.lojaslongoestoque.application.requests.ProductRequest
import lojas.longo.lojaslongoestoque.application.usecases.CreateProductUseCase
import lojas.longo.lojaslongoestoque.application.usecases.FindProductByIdUseCase
import lojas.longo.lojaslongoestoque.core.entity.Product
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/api/product")
class ProductController(private val createProductUseCase: CreateProductUseCase, private val findProductByIdUseCase: FindProductByIdUseCase) {
@PostMapping("/create")
fun createUser(@RequestBody productRequest: ProductRequest): Product {
return createProductUseCase.execute(productRequest.name,productRequest.size,productRequest.brand,productRequest.color,productRequest.gender)
}
@GetMapping("{id}")
fun getProduct(@PathVariable id:Long): Product?{
return findProductByIdUseCase.exeecute(id)
}
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/controller/ProductController.kt | 686602749 |
// Pacote da Camada de Aplicação - Controlador
package lojas.longo.lojaslongoestoque.application.controller
import lojas.longo.lojaslongoestoque.application.requests.UserRequest
import lojas.longo.lojaslongoestoque.application.usecases.CreateUserUseCase
import lojas.longo.lojaslongoestoque.application.usecases.FindUserByIdUseCase
import lojas.longo.lojaslongoestoque.core.entity.User
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/api/users")
class UserController(private val createUserUseCase: CreateUserUseCase,private val findUserByIdUseCase: FindUserByIdUseCase) {
@PostMapping("/create")
fun createUser(@RequestBody userRequest: UserRequest): User {
return createUserUseCase.execute(userRequest.username, userRequest.password)
}
@GetMapping("/{id}")
fun getUser(@PathVariable id: Long): User? {
return findUserByIdUseCase.execute(id)
}
}
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/controller/UserController.kt | 3394195707 |
package lojas.longo.lojaslongoestoque.application.requests
data class UserRequest(val username: String, val password: String)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/requests/UserRequest.kt | 1516887322 |
package lojas.longo.lojaslongoestoque.application.requests
data class ProductRequest(val name:String ,val nome:String, val size:String,val brand: String, val color:String, val gender:String)
| ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/requests/ProductRequest.kt | 751646077 |
package lojas.longo.lojaslongoestoque.application.usecases
import lojas.longo.lojaslongoestoque.core.entity.Product
interface CreateProductUseCase {
fun execute(name:String,size: String,brand: String,color:String,gender:String): Product
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/usecases/CreateProductUseCase.kt | 3137935991 |
package lojas.longo.lojaslongoestoque.application.usecases
import lojas.longo.lojaslongoestoque.core.entity.Product
interface FindProductByIdUseCase {
fun exeecute(id:Long): Product?
} | ApiGestaoProdutosUsuarios/src/main/kotlin/api/cleancode/api/application/usecases/FindProductByIdUseCase.kt | 112808156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.