path
stringlengths 4
242
| contentHash
stringlengths 1
10
| content
stringlengths 0
3.9M
|
---|---|---|
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/MultiSensor.kt | 81104945 | package com.k21091.wearsensing.presentation
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.wear.compose.material.AutoCenteringParams
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.Vignette
import androidx.wear.compose.material.VignettePosition
import androidx.wear.compose.material.rememberScalingLazyListState
import com.google.android.gms.wearable.Node
import com.k21091.wearsensing.presentation.theme.WearSensingTheme
class MultiSensor: ComponentActivity(), SensorEventListener {
private lateinit var sensorManager: SensorManager
private var AccSensor: Sensor? = null
private var GyroSensor: Sensor? = null
private var HeartRateSensor: Sensor? = null
private var LightSensor: Sensor? = null
var nodeSet: MutableSet<Node> = mutableSetOf()
var senddata=SendData(this,nodeSet)
val globalvariable = GlobalVariable.getInstance()
private var tag="multi"
private lateinit var accDataArray: Array<MutableState<String>>
private lateinit var gyroDataArray: Array<MutableState<String>>
private lateinit var heartrateDataArray: Array<MutableState<String>>
private lateinit var lightDataArray: Array<MutableState<String>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
accDataArray = Array(3) { remember { mutableStateOf("データが取れませんでした") } }
gyroDataArray = Array(3) { remember { mutableStateOf("データが取れませんでした") } }
heartrateDataArray = Array(3) { remember { mutableStateOf("データが取れませんでした") } }
heartrateDataArray[0].value =""
heartrateDataArray[2].value =""
lightDataArray = Array(3) { remember { mutableStateOf("データが取れませんでした") } }
lightDataArray[0].value =""
lightDataArray[2].value =""
WearApp()
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
AccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)
GyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
HeartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)
LightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
globalvariable.mode="false"
senddata.setupSendMessage()
}
//センサーに何かしらのイベントが発生したときに呼ばれる
override fun onSensorChanged(event: SensorEvent) {
if(globalvariable.isAccSensorEnabled&&::accDataArray.isInitialized){
sendthreedata("acc",accDataArray,event,Sensor.TYPE_LINEAR_ACCELERATION)
}
if(globalvariable.isGyroSensorEnabled&&::gyroDataArray.isInitialized){
sendthreedata("gyro",gyroDataArray,event,Sensor.TYPE_GYROSCOPE)
}
if(globalvariable.isHeartRateSensorEnabled&&::heartrateDataArray.isInitialized){
sendonedata("heart_rate",heartrateDataArray,event,Sensor.TYPE_HEART_RATE)
}
if(globalvariable.isLightSensorEnabled&&::lightDataArray.isInitialized){
sendonedata("light",lightDataArray,event,Sensor.TYPE_LIGHT)
}
when (globalvariable.mode) {
"start" -> {
senddata.sendSensorData(tag,"start")
globalvariable.mode="else"
}
"finish" -> {
senddata.sendSensorData(tag,"finish")
globalvariable.mode="else"
}
}
}
//センサの精度が変更されたときに呼ばれる
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
override fun onResume() {
super.onResume()
//リスナーとセンサーオブジェクトを渡す
//第一引数はインターフェースを継承したクラス、今回はthis
//第二引数は取得したセンサーオブジェクト
//第三引数は更新頻度 UIはUI表示向き、FASTはできるだけ早く、GAMEはゲーム向き
if (globalvariable.isAccSensorEnabled) {
sensorManager.registerListener(this, AccSensor, SensorManager.SENSOR_DELAY_UI)
}
if (globalvariable.isGyroSensorEnabled) {
sensorManager.registerListener(this, GyroSensor, SensorManager.SENSOR_DELAY_UI)
}
if (globalvariable.isHeartRateSensorEnabled) {
sensorManager.registerListener(this, HeartRateSensor, SensorManager.SENSOR_DELAY_UI)
}
if (globalvariable.isLightSensorEnabled) {
sensorManager.registerListener(this, LightSensor, SensorManager.SENSOR_DELAY_UI)
}
}
//アクティビティが閉じられたときにリスナーを解除する
override fun onPause() {
super.onPause()
//リスナーを解除しないとバックグラウンドにいるとき常にコールバックされ続ける
sensorManager.unregisterListener(this)
}
fun sendonedata(sensortype: String,DataArray: Array<MutableState<String>>,event: SensorEvent,useSensor: Int?) {
val sensor: Float
if (event.sensor.type === useSensor) {
sensor = event.values[0]
DataArray[0].value = " "
DataArray[1].value = "$sensor"
DataArray[2].value = " "
val log:String = System.currentTimeMillis().toString().plus(",").plus(sensor)
senddata.sendSensorData(log,sensortype)
}
}
fun sendthreedata(sensortype: String,DataArray: Array<MutableState<String>>,event: SensorEvent,useSensor: Int?){
val sensorX: Float
val sensorY: Float
val sensorZ: Float
if (event.sensor.type === useSensor) {
sensorX = event.values[0]
sensorY = event.values[1]
sensorZ = event.values[2]
DataArray[0].value = "X:$sensorX"
DataArray[1].value = "Y:$sensorY"
DataArray[2].value = "Z:$sensorZ"
val log:String = System.currentTimeMillis().toString().plus(",").plus(sensorX).plus(",").plus(sensorY).plus(",").plus(sensorZ)
senddata.sendSensorData(log,sensortype)
}
}
@Composable
fun WearApp() {
val chipText: MutableState<String> = remember {
mutableStateOf("記録開始")
}
WearSensingTheme {
// TODO: Swap to ScalingLazyListState
val listState = rememberScalingLazyListState()
val contentModifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
val iconModifier = Modifier
.size(24.dp)
.wrapContentSize(align = Alignment.Center)
/* *************************** Part 4: Wear OS Scaffold *************************** */
// TODO (Start): Create a Scaffold (Wear Version)
Scaffold(
vignette = {
// Only show a Vignette for scrollable screens. This code lab only has one screen,
// which is scrollable, so we show it all the time.
Vignette(vignettePosition = VignettePosition.TopAndBottom)
},
positionIndicator = {
PositionIndicator(
scalingLazyListState = listState
)
}
) {
// Modifiers used by our Wear composables.
val contentModifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
val iconModifier = Modifier
.size(24.dp)
.wrapContentSize(align = Alignment.Center)
/* *************************** Part 3: ScalingLazyColumn *************************** */
ScalingLazyColumn(
modifier = Modifier.fillMaxSize(),
autoCentering = AutoCenteringParams(itemIndex = 0),
state = listState
) {
val reusableComponents = ReusableComponents()
if (globalvariable.isAccSensorEnabled){
item { reusableComponents.MultiView(sensor = "加速度センサ", sensorDataArray = accDataArray, modifier = Modifier) }
}
if (globalvariable.isGyroSensorEnabled){
item { reusableComponents.MultiView(sensor = "ジャイロセンサ", sensorDataArray = gyroDataArray,modifier = Modifier) }
}
if (globalvariable.isHeartRateSensorEnabled){
item { reusableComponents.MultiView(sensor = "心拍センサ", sensorDataArray = heartrateDataArray, modifier = Modifier) }
}
if (globalvariable.isLightSensorEnabled){
item { reusableComponents.MultiView(sensor = "照度センサ", sensorDataArray = lightDataArray,modifier = Modifier) }
}
val chipSizeModifier = Modifier
.padding(10.dp)
.fillMaxWidth() // 幅を親に合わせる
.aspectRatio(3f)
item { Chip(
modifier = chipSizeModifier,
onClick = {
if (chipText.value=="記録開始"){
globalvariable.mode="start"
chipText.value="記録終了"
}
else if (chipText.value=="記録終了"){
globalvariable.mode="finish"
chipText.value="記録開始"
}
},
label = {
Text(
text = chipText.value,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
)}
}
}
}
}
@Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true)
@Composable
fun SmallRoundPreview() {
WearApp()
}
@Preview(device = Devices.WEAR_OS_LARGE_ROUND, showSystemUi = true)
@Composable
fun LargeRoundPreview() {
WearApp()
}
} |
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/globalvariable.kt | 2869588997 | package com.k21091.wearsensing.presentation
import android.app.Application
class GlobalVariable :Application(){
var mode: String? = null
var isAccSensorEnabled: Boolean = false
var isGyroSensorEnabled: Boolean = false
var isHeartRateSensorEnabled: Boolean = false
var isLightSensorEnabled: Boolean = false
companion object {
private var instance : GlobalVariable? = null
fun getInstance(): GlobalVariable {
if (instance == null)
instance = GlobalVariable()
return instance!!
}
}
} |
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/theme/Color.kt | 1717289068 | package com.k21091.wearsensing.presentation.theme
import androidx.compose.ui.graphics.Color
import androidx.wear.compose.material.Colors
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Red400 = Color(0xFFCF6679)
internal val wearColorPalette: Colors = Colors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200,
secondaryVariant = Teal200,
error = Red400,
onPrimary = Color.Black,
onSecondary = Color.Black,
onError = Color.Black
) |
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/theme/Theme.kt | 3843381114 | package com.k21091.wearsensing.presentation.theme
import androidx.compose.runtime.Composable
import androidx.wear.compose.material.MaterialTheme
@Composable
fun WearSensingTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colors = wearColorPalette,
typography = Typography,
// For shapes, we generally recommend using the default Material Wear shapes which are
// optimized for round and non-round devices.
content = content
)
} |
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/theme/Type.kt | 176907895 | package com.k21091.wearsensing.presentation.theme
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.wear.compose.material.Typography
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) |
WearOS_Sensing/app/src/main/java/com/k21091/wearsensing/presentation/SendData.kt | 615514159 | package com.k21091.wearsensing.presentation
import android.content.Context
import com.google.android.gms.wearable.*
import android.util.Log
import com.google.android.gms.tasks.Task
class SendData(context: Context, nodeSet:MutableSet<Node>){
val context:Context = context
var nodeSet:MutableSet<Node> = nodeSet
fun setupSendMessage() {
val capabilityInfo: Task<CapabilityInfo> =
Wearable.getCapabilityClient(context)
.getCapability(
"sensorCapabilities",// 中身は自由(後程使います)
CapabilityClient.FILTER_REACHABLE
)
capabilityInfo.addOnCompleteListener { task ->
if (task.isSuccessful) {
nodeSet = task.result.nodes
Log.d("setupSendMessage","successSetup, ".plus(nodeSet))
} else {
Log.d("setupSendMessage","defeatSetup")
}
}
}
// データを送信
fun sendSensorData(dataText: String, tag: String){
nodeSet.let {
pickBestNodeId(it)?.let { nodeId ->
val data = dataText.toByteArray(Charsets.UTF_8) //バイナリ変換
Wearable.getMessageClient(context)
.sendMessage(nodeId, tag, data)
.apply {
addOnSuccessListener {
// 送信成功
Log.d("sendSensorData","success")
}
addOnFailureListener {
// 送信失敗
Log.d("sendSensorData","defeat")
}
}
}
}
}
// 送信先として最適なノードを選択
private fun pickBestNodeId(nodes: Set<Node>): String? {
return nodes.firstOrNull { it.isNearby }?.id ?: nodes.firstOrNull()?.id
}
} |
WearOS_Sensing/getsensing/src/androidTest/java/com/k21091/wearsensing/ExampleInstrumentedTest.kt | 2951659961 | package com.k21091.wearsensing
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.k21091.wearsensing", appContext.packageName)
}
} |
WearOS_Sensing/getsensing/src/test/java/com/k21091/wearsensing/ExampleUnitTest.kt | 3585499691 | package com.k21091.wearsensing
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)
}
} |
WearOS_Sensing/getsensing/src/main/java/com/k21091/wearsensing/MainActivity.kt | 3140604419 | package com.k21091.wearsensing
import android.annotation.SuppressLint
import com.google.android.gms.wearable.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.google.android.gms.wearable.MessageClient
class MainActivity : AppCompatActivity(), MessageClient.OnMessageReceivedListener {
val dataList: MutableList<String> = mutableListOf()
val accdataList: MutableList<String> = mutableListOf()
val gyrodataList: MutableList<String> = mutableListOf()
val heartratedataList: MutableList<String> = mutableListOf()
val lightdataList: MutableList<String> = mutableListOf()
lateinit var createCSV: CreateCSV
var send = false
var accstr = ""
var gyrostr = ""
var heartratestr=""
var lightstr=""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Wearable.getMessageClient(applicationContext).addListener(this)
createCSV=CreateCSV(this)
val Yes_Button: Button = findViewById(R.id.yes_button)
val No_Button: Button = findViewById(R.id.no_button)
val save_Text: TextView = findViewById(R.id.saveView)
Yes_Button.visibility = View.GONE
No_Button.visibility = View.GONE
save_Text.visibility = View.GONE
}
// 受信したメッセージからデータを整理し処理
@SuppressLint("SetTextI18n")
override fun onMessageReceived(messageEvent: MessageEvent) {
val sensorText: TextView = findViewById(R.id.textView)
val strtmp="""
$accstr
$gyrostr
$heartratestr
$lightstr
"""
sensorText.text = strtmp
when(messageEvent.path) {
// tag別に処理を変える
"acc" -> {
if (accdataList.isEmpty()) {
// リストが空の場合の処理
accdataList.add("time,x,y,z")
}
accstr=getThreeData("加速度センサ",messageEvent,accdataList)
}
"gyro" -> {
if (gyrodataList.isEmpty()) {
// リストが空の場合の処理
gyrodataList.add("time,x,y,z")
}
gyrostr=getThreeData("ジャイロセンサ",messageEvent,gyrodataList)
}
"heart_rate" ->{
if (heartratedataList.isEmpty()) {
// リストが空の場合の処理
heartratedataList.add("time,heart_rate")
}
heartratestr=getOneData("心拍センサ",messageEvent,heartratedataList)
}
"light" ->{
if (lightdataList.isEmpty()) {
// リストが空の場合の処理
lightdataList.add("time,light")
}
lightstr=getOneData("照度センサ",messageEvent,lightdataList)
}
"start" -> {
send=true
val rec_Text: TextView = findViewById(R.id.recView)
rec_Text.text="記録中"
}
"finish" -> {
Log.d("getdata","sendfin")
val data = messageEvent.data.toString(Charsets.UTF_8) //文字列に変換
val rec_Text: TextView = findViewById(R.id.recView)
val save_Text: TextView = findViewById(R.id.saveView)
val Yes_Button: Button = findViewById(R.id.yes_button)
val No_Button: Button = findViewById(R.id.no_button)
Yes_Button.visibility = View.VISIBLE
No_Button.visibility = View.VISIBLE
save_Text.visibility = View.VISIBLE
Yes_Button.setOnClickListener {
if(!accdataList.isEmpty()){
createCSV.writeText("acc",accdataList)
accdataList.clear()
}
if(!gyrodataList.isEmpty()){
createCSV.writeText("gyro",gyrodataList)
gyrodataList.clear()
}
if(!heartratedataList.isEmpty()){
createCSV.writeText("heartrate",heartratedataList)
heartratedataList.clear()
}
if(!lightdataList.isEmpty()){
createCSV.writeText("light",lightdataList)
lightdataList.clear()
}
Yes_Button.visibility = View.GONE
No_Button.visibility = View.GONE
save_Text.visibility = View.GONE
}
No_Button.setOnClickListener {
dataList.clear()
Yes_Button.visibility = View.GONE
No_Button.visibility = View.GONE
save_Text.visibility = View.GONE
}
send=false
rec_Text.text=""
}
}
}
fun getOneData(
sensorname: String,
messageEvent: MessageEvent,
dataList: MutableList<String>
): String {
// 心拍センサ
val data = messageEvent.data.toString(Charsets.UTF_8) //文字列に変換
if(send) {
dataList.add(data)
}
val value = data.split(",").dropLastWhile { it.isEmpty() }.toTypedArray()
val x = ""
val Data = value[1].toFloat()
val z = ""
return """$sensorname
$x
$Data
$z"""
}
fun getThreeData(
sensorname: String,
messageEvent: MessageEvent,
dataList: MutableList<String>
): String {
// 加速度センサ
val data = messageEvent.data.toString(Charsets.UTF_8) //文字列に変換
if (send) {
dataList.add(data)
}
//受け取ったデータmsgはコンマ区切りのcsv形式なので、value[]にそれぞれ格納します。
val value = data.split(",").dropLastWhile { it.isEmpty() }.toTypedArray()
val x = value[1].toFloat()
val y = value[2].toFloat()
val z = value[3].toFloat()
return """$sensorname
X: $x
Y: $y
Z: $z"""
}
} |
WearOS_Sensing/getsensing/src/main/java/com/k21091/wearsensing/CreateCSV.kt | 2352508573 | package com.k21091.wearsensing
import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.BufferedWriter
import java.io.FileWriter
import java.io.PrintWriter
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class CreateCSV(context: Context) {
private val TAG = "CreateCSV"
private val fileAppend: Boolean = true // true=追記, false=上書き
private val context: Context = context
private val extension: String = ".csv"
fun writeText(type: String, dataList: MutableList<String>) {
// 現在の日時を取得
val currentDateTime = LocalDateTime.now()
// フォーマットを指定して日時を文字列に変換
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedDateTime = currentDateTime.format(formatter)
val fileName = type + formattedDateTime
val filePath: String =
context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
.toString().plus("/").plus(fileName).plus(extension) // 内部ストレージのDocumentのURL
try {
val fil = FileWriter(filePath, fileAppend)
val pw = PrintWriter(BufferedWriter(fil))
dataList.forEach { row ->
pw.println(row)
}
pw.close()
// Log the success
Log.i(TAG, "CSV file successfully created at $filePath")
} catch (e: Exception) {
// Log any errors that occurred during file creation
Log.e(TAG, "Error creating CSV file: ${e.message}")
}
}
}
|
tezkor-interview-android-base/app/src/test/java/com/tezkor/interview/ExampleTest.kt | 276328609 | package com.tezkor.interview
class ExampleTest {
}
|
tezkor-interview-android-base/app/src/main/java/com/tezkor/interview/TestActivity.kt | 2827523094 | package com.tezkor.interview
import android.os.Bundle
import android.os.PersistableBundle
import androidx.appcompat.app.AppCompatActivity
class TestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
setContentView(R.layout.activity_test)
}
} |
PrimerasPantallas/app/src/androidTest/java/me/alex/loginpage/ExampleInstrumentedTest.kt | 2483592361 | package me.alex.loginpage
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("me.alex.loginpage", appContext.packageName)
}
} |
PrimerasPantallas/app/src/test/java/me/alex/loginpage/ExampleUnitTest.kt | 1215260310 | package me.alex.loginpage
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)
}
} |
PrimerasPantallas/app/src/main/java/me/alex/loginpage/MainActivity.kt | 4249990909 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class MainActivity : AppCompatActivity() {
private lateinit var CorreoElectronico: EditText
private lateinit var Contrasenia: EditText
private lateinit var IniciaSe: Button
private lateinit var Registrarse: Button
private lateinit var noPass: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CorreoElectronico = findViewById(R.id.CorreoElectronico)
Contrasenia = findViewById(R.id.Contrasenia)
IniciaSe = findViewById(R.id.IniciaSe)
Registrarse = findViewById(R.id.Registrarse)
noPass = findViewById(R.id.noPass)
IniciaSe.setOnClickListener {
if (CorreoElectronico.text.isNotEmpty() && Contrasenia.text.isNotEmpty()) {
FirebaseAuth.getInstance().signInWithEmailAndPassword(CorreoElectronico.text.toString(),
Contrasenia.text.toString()).addOnCompleteListener {
if (it.isSuccessful) {
iniciarSesion (it.result?.user?.email ?: "")
} else {
error()
}
}
} else {
error()
}
}
Registrarse.setOnClickListener {
val intent = Intent(this, RegistroActivity::class.java)
startActivity(intent)
}
noPass.setOnClickListener {
val intent = Intent(this, MainActivityRecuperarPassword::class.java)
startActivity(intent)
}
}
private fun iniciarSesion(email: String){
val intent = Intent (this, InicioAlumnosActivity::class.java).apply {
putExtra("email", email)
}
startActivity(intent)
}
private fun error() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Usuario o contraseña incorrecto")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/RegistroAlumnosActivity.kt | 1918660796 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class RegistroAlumnosActivity : AppCompatActivity() {
private lateinit var nombrePerfilEditText: TextInputEditText
private lateinit var emailperfil: TextInputEditText
private lateinit var passwordEditText: TextInputEditText
private lateinit var confirmPasswordEditText: TextInputEditText
private lateinit var registerButton: AppCompatButton
private lateinit var loginTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registro_alumnos)
nombrePerfilEditText = findViewById(R.id.nombrePerfilEditText)
emailperfil = findViewById(R.id.emailperfil)
passwordEditText = findViewById(R.id.passwordEditText)
confirmPasswordEditText = findViewById(R.id.confirmPasswordEditText)
registerButton = findViewById(R.id.registerButton)
loginTextView = findViewById(R.id.loginTextView)
registerButton.setOnClickListener {
if (nombrePerfilEditText.text.toString().isNotEmpty() && emailperfil.text.toString().isNotEmpty() && passwordEditText.text.toString().isNotEmpty() && confirmPasswordEditText.text.toString().isNotEmpty()) {
if(passwordEditText.text.toString().equals(confirmPasswordEditText.text.toString())){
if (passwordEditText.text.toString().length >= 6){
FirebaseAuth.getInstance().createUserWithEmailAndPassword (emailperfil.text.toString(),
passwordEditText.text.toString()).addOnCompleteListener {
if (it.isSuccessful) {
val map: MutableMap<String, Any> = HashMap()
map["nombre"] = nombrePerfilEditText.text.toString()
map["correo"] = emailperfil.text.toString()
map["contraseña"] = passwordEditText.text.toString()
val id: String? = FirebaseAuth.getInstance().currentUser?.uid
FirebaseDatabase.getInstance().getReference().child("Alumnos").child(id.toString()).setValue(map).addOnCompleteListener{
if (it.isSuccessful) {
val intent = Intent(this, InicioAlumnosActivity::class.java)
startActivity(intent)
}
}
} else {
showAlert()
}
}
} else {
showAlert2()
}
}else{
showAlert3()
}
}else{
showAlert4()
}
}
loginTextView.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
private fun showAlert() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Se ha producido un error registrando al usuario")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert2() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("La contraseña debe tener al menos 6 caracteres")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert3() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Las contraseñas no coinciden")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert4() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Debes completar todos los datos")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/InicioAlumnosActivity.kt | 2062441604 | package me.alex.loginpage
import android.os.Bundle
import android.widget.ImageView
import android.widget.SearchView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class InicioAlumnosActivity : AppCompatActivity() {
private lateinit var textView: TextView
private lateinit var imageView2: ImageView
private lateinit var textViewGreeting: TextView
private lateinit var searchView: SearchView
private lateinit var textView4: TextView
private lateinit var imageView6: ImageView
private lateinit var textView7: TextView
private lateinit var imageView7: ImageView
private lateinit var imageView8: ImageView
private lateinit var imageView9: ImageView
private lateinit var textView8: TextView
private lateinit var textView9: TextView
private lateinit var textView10: TextView
private lateinit var imageView10: ImageView
private lateinit var textView13: TextView
private lateinit var imageView11: ImageView
private lateinit var textView14: TextView
private lateinit var imageView12: ImageView
private lateinit var textView15: TextView
private lateinit var imageView13: ImageView
private lateinit var textView16: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_inicio_alumnos)
textView = findViewById(R.id.loginTextView)
imageView2 = findViewById(R.id.imageView2)
textViewGreeting = findViewById(R.id.textViewGreeting)
searchView = findViewById(R.id.searchView)
textView4 = findViewById(R.id.textView4)
imageView6 = findViewById(R.id.imageView6)
textView7 = findViewById(R.id.textView7)
imageView7 = findViewById(R.id.imageView7)
imageView8 = findViewById(R.id.imageView8)
imageView9 = findViewById(R.id.imageView9)
textView8 = findViewById(R.id.textView8)
textView9 = findViewById(R.id.textView9)
textView10 = findViewById(R.id.textView10)
imageView10 = findViewById(R.id.imageView10)
textView13 = findViewById(R.id.textView13)
imageView11 = findViewById(R.id.imageView11)
textView14 = findViewById(R.id.textView14)
imageView12 = findViewById(R.id.imageView12)
textView15 = findViewById(R.id.textView15)
imageView13 = findViewById(R.id.imageView13)
textView16 = findViewById(R.id.textView16)
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/RegistroActivity.kt | 1304273845 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
class RegistroActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registro)
val textView6 = findViewById<TextView>(R.id.textView6)
val button6 = findViewById<Button>(R.id.button6)
val button7 = findViewById<Button>(R.id.button7)
val imageView5 = findViewById<ImageView>(R.id.imageView5)
button6.setOnClickListener {
val intent = Intent(this, RegistroMaestrosActivity::class.java)
startActivity(intent)
}
button7.setOnClickListener {
val intent = Intent(this, RegistroAlumnosActivity::class.java)
startActivity(intent)
}
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/MainActivityPaginaPrincipal.kt | 3866268956 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.ImageView
import me.alex.loginpage.R
class MainActivityPaginaPrincipal : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_pagina_principal)
val imageView14 = findViewById<ImageView>(R.id.imageView14)
imageView14.setOnClickListener {
// Crea un Intent para iniciar la actividad MainActivity
val intent = Intent(this, MainActivity::class.java)
// Inicia la nueva actividad
startActivity(intent)
}
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/RegistroMaestrosActivity.kt | 1905410525 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class RegistroMaestrosActivity : AppCompatActivity() {
private lateinit var nombrePerfil: TextInputEditText
private lateinit var correoEditText: TextInputEditText
private lateinit var passwordEdit: TextInputEditText
private lateinit var confirmPasswordEdit: TextInputEditText
private lateinit var curpEditText: TextInputEditText
private lateinit var register: AppCompatButton
private lateinit var loginText: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registro_maestros)
nombrePerfil = findViewById(R.id.nombrePerfil)
correoEditText = findViewById(R.id.correoEditText)
passwordEdit = findViewById(R.id.passwordEdit)
confirmPasswordEdit = findViewById(R.id.confirmPasswordEdit)
curpEditText = findViewById(R.id.curpEditText)
register = findViewById(R.id.register)
loginText = findViewById(R.id.loginText)
register.setOnClickListener {
if (nombrePerfil.text.toString().isNotEmpty() && correoEditText.text.toString().isNotEmpty() && passwordEdit.text.toString().isNotEmpty() && confirmPasswordEdit.text.toString().isNotEmpty() && curpEditText.text.toString().isNotEmpty()) {
if(passwordEdit.text.toString().equals(confirmPasswordEdit.text.toString())){
if (passwordEdit.text.toString().length >= 6){
FirebaseAuth.getInstance().createUserWithEmailAndPassword (correoEditText.text.toString(),
passwordEdit.text.toString()).addOnCompleteListener {
if (it.isSuccessful) {
val map: MutableMap<String, Any> = HashMap()
map["nombre"] = nombrePerfil.text.toString()
map["curp"] = curpEditText.text.toString()
map["correo"] = correoEditText.text.toString()
map["contraseña"] = passwordEdit.text.toString()
val id: String? = FirebaseAuth.getInstance().currentUser?.uid
FirebaseDatabase.getInstance().getReference().child("Maestros").child(id.toString()).setValue(map).addOnCompleteListener{
if (it.isSuccessful) {
val intent = Intent(this, InicioAlumnosActivity::class.java)
startActivity(intent)
}
}
} else {
showAlert()
}
}
}else{
showAlert2()
}
}else{
showAlert3()
}
}else{
showAlert4()
}
}
loginText.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
private fun showHome(email: String){
val intent = Intent (this, MainActivity::class.java).apply {
putExtra("email", email)
}
startActivity(intent)
}
private fun showAlert() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Se ha producido un error registrando al usuario")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert2() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("La contraseña debe tener al menos 6 caracteres")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert3() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Las contraseñas no coinciden")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showAlert4() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Debes completar todos los datos")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/MainActivity4.kt | 2158337446 | package me.alex.loginpage
import android.os.Bundle
import android.widget.ImageView
import android.widget.SearchView
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import me.alex.loginpage.R
import androidx.constraintlayout.widget.ConstraintLayout
class MainActivity4 : AppCompatActivity() {
private lateinit var imageView20: ImageView
private lateinit var textView17: TextView
private lateinit var textView18: TextView
private lateinit var ratingBar: androidx.appcompat.widget.AppCompatRatingBar
private lateinit var imageView21: ImageView
private lateinit var textView20: TextView
private lateinit var textView19: TextView
private lateinit var ratingBar2: androidx.appcompat.widget.AppCompatRatingBar
private lateinit var imageView22: ImageView
private lateinit var textView22: TextView
private lateinit var textView21: TextView
private lateinit var ratingBar3: androidx.appcompat.widget.AppCompatRatingBar
private lateinit var imageView24: ImageView
private lateinit var textView24: TextView
private lateinit var textView23: TextView
private lateinit var ratingBar4: androidx.appcompat.widget.AppCompatRatingBar
private lateinit var searchView: SearchView
private lateinit var spinner4: Spinner
private lateinit var textView11: TextView
private lateinit var textView12: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main4)
imageView20 = findViewById(R.id.imageView20)
textView17 = findViewById(R.id.textView17)
textView18 = findViewById(R.id.textView18)
imageView21 = findViewById(R.id.imageView21)
textView20 = findViewById(R.id.textView20)
textView19 = findViewById(R.id.textView19)
imageView22 = findViewById(R.id.imageView22)
textView22 = findViewById(R.id.textView22)
textView21 = findViewById(R.id.textView21)
imageView24 = findViewById(R.id.imageView24)
textView24 = findViewById(R.id.textView24)
textView23 = findViewById(R.id.textView23)
searchView = findViewById(R.id.searchView)
spinner4 = findViewById(R.id.spinner4)
textView11 = findViewById(R.id.textView11)
textView12 = findViewById(R.id.textView12)
}
}
|
PrimerasPantallas/app/src/main/java/me/alex/loginpage/MainActivityRecuperarPassword.kt | 3743837239 | package me.alex.loginpage
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.auth.FirebaseAuth
class MainActivityRecuperarPassword : AppCompatActivity() {
private lateinit var nombrePerfilEditText : TextInputEditText
private lateinit var button3 : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_recuperar_password)
nombrePerfilEditText = findViewById(R.id.nombrePerfilEditText)
button3 = findViewById(R.id.button3)
button3.setOnClickListener{
validacion()
}
}
private fun validacion() {
val correo = nombrePerfilEditText.text.toString()
if(correo.isNotEmpty()){
enviarcorreo(correo)
}
}
private fun enviarcorreo(correo: String) {
FirebaseAuth.getInstance().sendPasswordResetEmail(correo).addOnCompleteListener {
if(it.isSuccessful){
Toast.makeText(this, "Correo enviado", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}else{
showAlert2()
}
}
}
private fun showAlert2() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Error")
builder.setMessage("Correo invalido")
builder.setPositiveButton("Aceptar", null)
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
|
TokenBucket/shared/src/iosMain/kotlin/io/silv/tokenbucket/Platform.ios.kt | 168648171 | package io.silv.tokenbucket
import kotlin.experimental.ExperimentalNativeApi
import kotlin.time.TimeSource
internal actual fun platformNanoTime(): Long = TimeSource.Monotonic.markNow().elapsedNow().inWholeNanoseconds
@OptIn(ExperimentalNativeApi::class)
internal actual inline fun assert(value: Boolean, lazyMessage:() -> String) {
kotlin.assert(value, lazyMessage)
} |
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/Platform.kt | 1436082048 | package io.silv.tokenbucket
internal expect fun platformNanoTime(): Long
internal expect inline fun assert(value: Boolean, lazyMessage: () -> String) |
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/TokenBucketImpl.kt | 2569572337 | package io.silv.tokenbucket
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* A token bucket implementation that is of a leaky bucket in the sense that it has a finite capacity and any added
* tokens that would exceed this capacity will "overflow" out of the bucket and are lost forever.
*
*
* In this implementation the rules for refilling the bucket are encapsulated in a provided `RefillStrategy`
* instance. Prior to attempting to consume any tokens the refill strategy will be consulted to see how many tokens
* should be added to the bucket.
*
*
* In addition in this implementation the method of yielding CPU control is encapsulated in the provided
* `SleepStrategy` instance. For high performance applications where tokens are being refilled incredibly quickly
* and an accurate bucket implementation is required, it may be useful to never yield control of the CPU and to instead
* busy wait. This strategy allows the caller to make this decision for themselves instead of the library forcing a
* decision.
*/
internal class TokenBucketImpl(
/**
* Returns the capacity of this token bucket. This is the maximum number of tokens that the bucket can hold at
* any one time.
*
* @return The capacity of the bucket.
*/
override val capacity: Long,
initialTokens: Long,
private val refillStrategy: TokenBucket.RefillStrategy,
private val sleepStrategy: TokenBucket.SleepStrategy
) :
TokenBucket {
private val numTokensMutex= Mutex()
private val refillMutex = Mutex()
private val consumeMutex = Mutex()
private var size: Long = initialTokens
init {
assert(capacity > 0) { "capacity was less than 0" }
assert(initialTokens <= capacity) { "initial tokens exceed capacity" }
}
/**
* Returns the current number of tokens in the bucket. If the bucket is empty then this method will return 0.
*
* @return The current number of tokens in the bucket.
*/
override suspend fun numTokens(): Long {
// Give the refill strategy a chance to add tokens if it needs to so that we have an accurate
// count.
return numTokensMutex.withLock {
refill(refillStrategy.refill())
size
}
}
/**
* Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
* bucket.
*
* @see TokenBucket.RefillStrategy.getNanosUntilNextRefill
* @return The amount of time until the next group of tokens can be added to the token bucket.
*/
@Throws(UnsupportedOperationException::class)
override fun getNanosUntilNextRefill(): Long {
return refillStrategy.getNanosUntilNextRefill()
}
/**
* Attempt to consume a single token from the bucket. If it was consumed then `true` is returned, otherwise
* `false` is returned.
*
* @return `true` if a token was consumed, `false` otherwise.
*/
override suspend fun tryConsume(): Boolean {
return tryConsume(1)
}
/**
* Attempt to consume a specified number of tokens from the bucket. If the tokens were consumed then `true`
* is returned, otherwise `false` is returned.
*
* @param numTokens The number of tokens to consume from the bucket, must be a positive number.
* @return `true` if the tokens were consumed, `false` otherwise.
*/
override suspend fun tryConsume(numTokens: Long): Boolean {
consumeMutex.withLock {
assert(numTokens > 0) { "Number of tokens to consume must be positive" }
assert(numTokens <= capacity) { "Number of tokens to consume must be less than the capacity of the bucket." }
refill(refillStrategy.refill())
// Now try to consume some tokens
if (numTokens <= size) {
size -= numTokens
return true
}
return false
}
}
/**
* Consume a single token from the bucket. If no token is currently available then this method will block until a
* token becomes available.
*/
override suspend fun consume() {
consume(1)
}
/**
* Consumes multiple tokens from the bucket. If enough tokens are not currently available then this method will block
* until
*
* @param numTokens The number of tokens to consume from teh bucket, must be a positive number.
*/
override suspend fun consume(numTokens: Long) {
while (true) {
if (tryConsume(numTokens)) {
break
}
sleepStrategy.sleep()
}
}
/**
* Refills the bucket with the specified number of tokens. If the bucket is currently full or near capacity then
* fewer than `numTokens` may be added.
*
* @param numTokens The number of tokens to add to the bucket.
*/
override suspend fun refill(numTokens: Long) {
refillMutex.withLock {
val newTokens = capacity.coerceAtMost(numTokens.coerceAtLeast(0))
size = (size + newTokens).coerceAtMost(capacity).coerceAtLeast(0)
}
}
} |
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/Ticker.kt | 859512013 | package io.silv.tokenbucket
interface Ticker {
fun read(): Long
companion object {
/**
* A ticker that reads the current time using [platformNanoTime].
*
* @since 10.0
*/
fun systemTicker(): Ticker {
return SYSTEM_TICKER
}
private val SYSTEM_TICKER: Ticker = object : Ticker {
override fun read(): Long {
return platformNanoTime()
}
}
}
}
|
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/TokenBucket.kt | 1710809984 | package io.silv.tokenbucket
/**
* A token bucket is used for rate limiting access to a portion of code.
*
* @see [Token Bucket on Wikipedia](http://en.wikipedia.org/wiki/Token_bucket)
*
* @see [Leaky Bucket on Wikipedia](http://en.wikipedia.org/wiki/Leaky_bucket)
*/
public interface TokenBucket {
/**
* Returns the capacity of this token bucket. This is the maximum number of tokens that the bucket can hold at
* any one time.
*
* @return The capacity of the bucket.
*/
val capacity: Long
/**
* Returns the current number of tokens in the bucket. If the bucket is empty then this method will return 0.
*
* @return The current number of tokens in the bucket.
*/
suspend fun numTokens(): Long
/**
* Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
* bucket.
*
* @see TokenBucket.RefillStrategy.getNanosUntilNextRefill
* @return The amount of time until the next group of tokens can be added to the token bucket.
*/
@Throws(UnsupportedOperationException::class)
fun getNanosUntilNextRefill(): Long
/**
* Attempt to consume a single token from the bucket. If it was consumed then `true` is returned, otherwise
* `false` is returned.
*
* @return `true` if a token was consumed, `false` otherwise.
*/
suspend fun tryConsume(): Boolean
/**
* Attempt to consume a specified number of tokens from the bucket. If the tokens were consumed then `true`
* is returned, otherwise `false` is returned.
*
* @param numTokens The number of tokens to consume from the bucket, must be a positive number.
* @return `true` if the tokens were consumed, `false` otherwise.
*/
suspend fun tryConsume(numTokens: Long): Boolean
/**
* Consume a single token from the bucket. If no token is currently available then this method will block until a
* token becomes available.
*/
suspend fun consume()
/**
* Consumes multiple tokens from the bucket. If enough tokens are not currently available then this method will block
* until
*
* @param numTokens The number of tokens to consume from the bucket, must be a positive number.
*/
suspend fun consume(numTokens: Long)
/**
* Refills the bucket with the specified number of tokens. If the bucket is currently full or near capacity then
* fewer than `numTokens` may be added.
*
* @param numTokens The number of tokens to add to the bucket.
*/
suspend fun refill(numTokens: Long)
/** Encapsulation of a refilling strategy for a token bucket. */
public interface RefillStrategy {
/**
* Returns the number of tokens to add to the token bucket.
*
* @return The number of tokens to add to the token bucket.
*/
suspend fun refill(): Long
/**
* Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
* bucket. Please note, depending on the `SleepStrategy` used by the token bucket, tokens may not actually
* be added until much after the returned duration. If for some reason the implementation of
* `RefillStrategy` doesn't support knowing when the next batch of tokens will be added, then an
* `UnsupportedOperationException` may be thrown. Lastly, if the duration until the next time tokens will
* be added to the token bucket is less than a single unit of the passed in time unit then this method will
* return 0.
*
* @return The amount of time in nanoseconds until the next group of tokens can be added to the token bucket.
*/
@Throws(UnsupportedOperationException::class)
fun getNanosUntilNextRefill(): Long
}
/** Encapsulation of a strategy for relinquishing control of the CPU. */
public interface SleepStrategy {
/**
* Sleep for a short period of time to allow other threads and system processes to execute.
*/
suspend fun sleep()
}
} |
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/TokenBuckets.kt | 281461220 | package io.silv.tokenbucket
import kotlinx.coroutines.delay
/** Static utility methods pertaining to creating [TokenBucketImpl] instances. */
public object TokenBuckets {
/** Create a new builder for token buckets. */
fun builder(): Builder {
return Builder()
}
private val YIELDING_SLEEP_STRATEGY: TokenBucket.SleepStrategy =
object : TokenBucket.SleepStrategy {
override suspend fun sleep() {
// Sleep for the smallest unit of time possible
// internally anything less than 1 millisecond will be rounded
delay(1)
}
}
private val BUSY_WAIT_SLEEP_STRATEGY: TokenBucket.SleepStrategy =
object : TokenBucket.SleepStrategy {
override suspend fun sleep() {
// Do nothing, don't sleep.
}
}
class Builder {
private var capacity: Long? = null
private var initialTokens: Long = 0
private var refillStrategy: TokenBucket.RefillStrategy? = null
private var sleepStrategy = YIELDING_SLEEP_STRATEGY
private val ticker = Ticker.systemTicker()
/** Specify the overall capacity of the token bucket. */
fun withCapacity(numTokens: Long): Builder {
assert(numTokens > 0) { "Must specify a positive number of tokens" }
capacity = numTokens
return this
}
/** Initialize the token bucket with a specific number of tokens. */
fun withInitialTokens(numTokens: Long): Builder {
assert(numTokens > 0) { "Must specify a positive number of tokens" }
initialTokens = numTokens
return this
}
/** Refill tokens at a fixed interval. */
fun withFixedIntervalRefillStrategy(
refillTokens: Long,
periodNanos: Long,
): Builder {
return withRefillStrategy(
FixedIntervalRefillStrategy(
ticker,
refillTokens,
periodNanos,
)
)
}
/** Use a user defined refill strategy. */
fun withRefillStrategy(refillStrategy: TokenBucket.RefillStrategy): Builder {
this.refillStrategy = refillStrategy
return this
}
/** Use a sleep strategy that will always attempt to yield the CPU to other processes. */
fun withYieldingSleepStrategy(): Builder {
return withSleepStrategy(YIELDING_SLEEP_STRATEGY)
}
/**
* Use a sleep strategy that will not yield the CPU to other processes. It will busy wait until more tokens become
* available.
*/
fun withBusyWaitSleepStrategy(): Builder {
return withSleepStrategy(BUSY_WAIT_SLEEP_STRATEGY)
}
/** Use a user defined sleep strategy. */
fun withSleepStrategy(sleepStrategy: TokenBucket.SleepStrategy): Builder {
this.sleepStrategy = sleepStrategy
return this
}
/** Build the token bucket. */
fun build(): TokenBucket {
checkNotNull(capacity) { "Must specify a capacity" }
checkNotNull(refillStrategy) { "Must specify a refill strategy" }
return TokenBucketImpl(
capacity!!,
initialTokens,
refillStrategy!!,
sleepStrategy)
}
}
} |
TokenBucket/shared/src/commonMain/kotlin/io/silv/tokenbucket/FixedIntervalRefillStrategy.kt | 1131167271 | package io.silv.tokenbucket
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* A token bucket refill strategy that will provide N tokens for a token bucket to consume every T units of time.
* The tokens are refilled in bursts rather than at a fixed rate. This refill strategy will never allow more than
* N tokens to be consumed during a window of time T.
*/
class FixedIntervalRefillStrategy(
private val ticker: Ticker,
private val numTokensPerPeriod: Long,
private val periodNanos: Long,
) : TokenBucket.RefillStrategy {
private val mutex = Mutex()
private var lastRefillTime: Long = -periodNanos
private var nextRefillTime: Long = -periodNanos
override suspend fun refill(): Long {
return mutex.withLock {
val now = ticker.read()
if (now < nextRefillTime) {
return 0
}
// We now know that we need to refill the bucket with some tokens, the question is how many. We need to count how
// many periods worth of tokens we've missed.
val numPeriods = ((now - lastRefillTime) / periodNanos).coerceAtLeast(0)
// Move the last refill time forward by this many periods.
lastRefillTime += numPeriods * periodNanos
// ...and we'll refill again one period after the last time we refilled.
nextRefillTime = lastRefillTime + periodNanos
numPeriods * numTokensPerPeriod
}
}
override fun getNanosUntilNextRefill(): Long {
val now = ticker.read()
return (nextRefillTime - now).coerceAtLeast(0)
}
} |
TokenBucket/shared/src/androidMain/kotlin/io/silv/tokenbucket/Platform.android.kt | 2618063851 | package io.silv.tokenbucket
internal actual fun platformNanoTime(): Long = System.nanoTime()
internal actual inline fun assert(value: Boolean, lazyMessage:() -> String) {
kotlin.assert(value, lazyMessage)
} |
TokenBucket/token-bucket-ktor/src/main/kotlin/io/silv/token_bucket_ktor/Plugin.kt | 660036799 | package io.silv.token_bucket_ktor
import io.ktor.client.plugins.api.ClientPlugin
import io.ktor.client.plugins.api.createClientPlugin
import io.silv.tokenbucket.TokenBuckets
import kotlinx.coroutines.ensureActive
import kotlin.coroutines.coroutineContext
class TokenBucketPluginConfig {
var consumptionAmount: Long = 1L
var bucket: TokenBuckets.Builder.() -> Unit = {}
}
val TokenBucketPlugin: ClientPlugin<TokenBucketPluginConfig> =
createClientPlugin("TokenBucketPlugin", ::TokenBucketPluginConfig) {
val numTokens = pluginConfig.consumptionAmount
val bucket = TokenBuckets.Builder().apply(pluginConfig.bucket).build()
onRequest { _, _->
coroutineContext.ensureActive()
bucket.consume(numTokens)
coroutineContext.ensureActive()
}
} |
ExamenFinalPmmDam2/app/src/androidTest/java/com/example/examenfinalpmmdam2/ExampleInstrumentedTest.kt | 1239431414 | package com.example.examenfinalpmmdam2
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.examenfinalpmmdam2", appContext.packageName)
}
} |
ExamenFinalPmmDam2/app/src/test/java/com/example/examenfinalpmmdam2/ExampleUnitTest.kt | 1183092385 | package com.example.examenfinalpmmdam2
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)
}
} |
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/ThirdActivity.kt | 3225267923 | package com.example.examenfinalpmmdam2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class ThirdActivity : AppCompatActivity() {
private lateinit var txvVideojuego: TextView
private lateinit var botonVolver: Button
private lateinit var botonGuardar: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_third)
txvVideojuego = findViewById(R.id.txvvideojuego)
botonVolver = findViewById(R.id.botonvolver)
botonGuardar = findViewById(R.id.botonguardar)
var db = DBManager(this)
val videojuego = intent.getSerializableExtra("videojuego") as Videojuego
txvVideojuego.text = videojuego.toString()
botonVolver.setOnClickListener {
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
botonGuardar.setOnClickListener {
val intent = Intent(this,SaveActivity::class.java)
db.escribir(videojuego)
startActivity(intent)
}
}
} |
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/MainActivity.kt | 443164214 | package com.example.examenfinalpmmdam2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var edtNombre: EditText
private lateinit var edtValoracion: EditText
private lateinit var botonSiguiente: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edtNombre = findViewById(R.id.edtnombre)
edtValoracion = findViewById(R.id.edtvaloracion)
botonSiguiente = findViewById(R.id.botonsiguiente)
botonSiguiente.setOnClickListener {
if(!edtNombre.text.isNullOrBlank() && !edtValoracion.text.isNullOrBlank()){
if(edtValoracion.text.toString().toFloat() >= 0.00){
val intent = Intent(this,SecondActivity::class.java)
intent.putExtra("videojuego", Videojuego(edtNombre.text.toString(),edtValoracion.text.toString().toFloat(),null,null))
startActivity(intent)
}else{
Toast.makeText(this,"La valoracion no puede ser negativa", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this,"Introduzca todos los datos antes de continuar", Toast.LENGTH_SHORT).show()
}
}
}
} |
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/DBManager.kt | 3549036385 | package com.example.examenfinalpmmdam2
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
// Clase DatabaseHelper
class DBManager (context: Context) : SQLiteOpenHelper(context, DATABASE, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 1
private const val DATABASE = "videojuegos.db"
private const val TABLA_NAME = "Videojuegos"
private const val KEY_ID = "_Id"
private const val COLUMN_NOMBRE = "nombre"
private const val COLUMN_VALORACION = "valoracion"
private const val COLUMN_DESARROLLADORA = "desarrolladora"
private const val COLUMN_ANO= "año"
}
override fun onCreate(db: SQLiteDatabase) {
val createTable = "CREATE TABLE $TABLA_NAME ($KEY_ID INTEGER PRIMARY KEY, $COLUMN_NOMBRE TEXT, $COLUMN_VALORACION NUMBER, $COLUMN_DESARROLLADORA TEXT,$COLUMN_ANO INTEGER)"
db.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $TABLA_NAME")
onCreate(db)
}
fun escribir(videojuego: Videojuego):Long{
val db = this.writableDatabase
val values = ContentValues().apply {
put(COLUMN_NOMBRE, videojuego.getNombre())
put(COLUMN_VALORACION,videojuego.getValoracion())
put(COLUMN_DESARROLLADORA, videojuego.getDesarrolladora())
put(COLUMN_ANO, videojuego.getAno())
}
val id= db.insert(TABLA_NAME, null, values)
db.close()
return id
}
@SuppressLint("Range")
fun lectura(): ArrayList<Videojuego> {
val lectura = ArrayList<Videojuego>()
val selectQuery = "SELECT * FROM $TABLA_NAME"
val db = this.readableDatabase
val cursor = db.rawQuery(selectQuery, null)
if (cursor.moveToFirst()) {
do {
val nombre = cursor.getString(cursor.getColumnIndex(COLUMN_NOMBRE))
val valoracion = cursor.getFloat(cursor.getColumnIndex(COLUMN_VALORACION))
val desarrolladora = cursor.getString(cursor.getColumnIndex(COLUMN_DESARROLLADORA))
val ano = cursor.getInt(cursor.getColumnIndex(COLUMN_ANO))
var videojuego = Videojuego(nombre,valoracion,desarrolladora,ano)
lectura.add(videojuego)
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return lectura
}
}
|
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/SaveActivity.kt | 3475447741 | package com.example.examenfinalpmmdam2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class SaveActivity : AppCompatActivity() {
private lateinit var txvVideojuegos: TextView
private lateinit var botonVolver: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_save)
txvVideojuegos = findViewById(R.id.txvvideojuegos)
botonVolver = findViewById(R.id.botonvolver)
var db = DBManager(this)
var videojuegos = db.lectura()
var listaVideojuegos:String =""
for (videojuego in videojuegos){
listaVideojuegos += videojuego.toString() +"\n"
}
txvVideojuegos.text = listaVideojuegos
botonVolver.setOnClickListener {
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
}
}
|
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/SecondActivity.kt | 4051028633 | package com.example.examenfinalpmmdam2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class SecondActivity : AppCompatActivity() {
private lateinit var edtDesarrolladora: EditText
private lateinit var edtAno: EditText
private lateinit var botonSiguiente: Button
private lateinit var botonVolver: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
edtDesarrolladora = findViewById(R.id.edtdesarrolladora)
edtAno = findViewById(R.id.edtaño)
botonSiguiente = findViewById(R.id.botonsiguiente)
botonVolver = findViewById(R.id.botonvolver)
botonSiguiente.setOnClickListener {
if(!edtDesarrolladora.text.isNullOrBlank() && !edtAno.text.isNullOrBlank()){
if(edtAno.text.toString().toInt() in 1900..2024){
val intent = Intent(this,ThirdActivity::class.java)
val videojuego = intent.getSerializableExtra("videojuego") as Videojuego
videojuego.setDesarrolladora(edtDesarrolladora.text.toString())
videojuego.setAno(edtAno.text.toString().toInt())
if(!videojuego.getNombre().isNullOrBlank() && !videojuego.getValoracion().toString().isNullOrBlank() && !videojuego.getDesarrolladora().isNullOrBlank() && !videojuego.getAno().toString().isNullOrBlank()){
intent.putExtra("videojuego", videojuego)
startActivity(intent)
}else{
Toast.makeText(this,"Error inesperado", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this,"El año no debe estar comprendido entre 1900 y 2024", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this,"Introduzca todos los datos antes de continuar", Toast.LENGTH_SHORT).show()
}
}
botonVolver.setOnClickListener {
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
}
} |
ExamenFinalPmmDam2/app/src/main/java/com/example/examenfinalpmmdam2/Videojuego.kt | 1444725044 | package com.example.examenfinalpmmdam2
import java.io.Serializable
class Videojuego(
private var nombre:String,
private var valoracion:Float,
private var desarrolladora: String?,
private var ano: Int?
):Serializable{
fun getNombre():String{
return nombre
}
fun getValoracion():Float{
return valoracion
}
fun getDesarrolladora(): String? {
return desarrolladora
}
fun getAno(): Int? {
return ano
}
fun setDesarrolladora(desarrolladora: String) {
this.desarrolladora = desarrolladora
}
fun setAno(ano: Int) {
this.ano = ano
}
override fun toString(): String {
return "Nombre: $nombre valoracion: $valoracion Desarrolladora: $desarrolladora Año: $ano"
}
} |
api-foodoptima/src/test/kotlin/com/foodoptima/ApplicationTest.kt | 627782763 | package com.foodoptima
import com.foodoptima.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}
|
api-foodoptima/src/main/kotlin/com/foodoptima/Application.kt | 438990858 | package com.foodoptima
import com.foodoptima.plugins.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
configureHTTP()
configureSerialization()
configureDatabases()
configureRouting()
}
|
api-foodoptima/src/main/kotlin/com/foodoptima/plugins/HTTP.kt | 3393430755 | package com.foodoptima.plugins
import io.ktor.server.application.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.routing.*
fun Application.configureHTTP() {
install(DefaultHeaders) {
header("X-Engine", "Ktor") // will send this header with each response
}
routing {
swaggerUI(path = "openapi")
}
}
|
api-foodoptima/src/main/kotlin/com/foodoptima/plugins/Routing.kt | 4010208319 | package com.foodoptima.plugins
import io.ktor.resources.*
import io.ktor.server.application.*
import io.ktor.server.resources.*
import io.ktor.server.resources.Resources
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
fun Application.configureRouting() {
install(Resources)
routing {
get("/") {
call.respondText("Hello World!")
}
get<Articles> { article ->
// Get all articles ...
call.respond("List of articles sorted starting from ${article.sort}")
}
}
}
@Serializable
@Resource("/articles")
class Articles(val sort: String? = "new")
|
api-foodoptima/src/main/kotlin/com/foodoptima/plugins/Serialization.kt | 3309431590 | package com.foodoptima.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
routing {
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
}
}
|
api-foodoptima/src/main/kotlin/com/foodoptima/plugins/Databases.kt | 3569481082 | package com.foodoptima.plugins
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.jetbrains.exposed.sql.*
fun Application.configureDatabases() {
val database = Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
user = "root",
driver = "org.h2.Driver",
password = ""
)
val userService = UserService(database)
routing {
// Create user
post("/users") {
val user = call.receive<ExposedUser>()
val id = userService.create(user)
call.respond(HttpStatusCode.Created, id)
}
// Read user
get("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
val user = userService.read(id)
if (user != null) {
call.respond(HttpStatusCode.OK, user)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
// Update user
put("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
val user = call.receive<ExposedUser>()
userService.update(id, user)
call.respond(HttpStatusCode.OK)
}
// Delete user
delete("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
userService.delete(id)
call.respond(HttpStatusCode.OK)
}
}
}
|
api-foodoptima/src/main/kotlin/com/foodoptima/plugins/UsersSchema.kt | 3977933949 | package com.foodoptima.plugins
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import kotlinx.serialization.Serializable
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
@Serializable
data class ExposedUser(val name: String, val age: Int)
class UserService(private val database: Database) {
object Users : Table() {
val id = integer("id").autoIncrement()
val name = varchar("name", length = 50)
val age = integer("age")
override val primaryKey = PrimaryKey(id)
}
init {
transaction(database) {
SchemaUtils.create(Users)
}
}
suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
suspend fun create(user: ExposedUser): Int = dbQuery {
Users.insert {
it[name] = user.name
it[age] = user.age
}[Users.id]
}
suspend fun read(id: Int): ExposedUser? {
return dbQuery {
Users.select { Users.id eq id }
.map { ExposedUser(it[Users.name], it[Users.age]) }
.singleOrNull()
}
}
suspend fun update(id: Int, user: ExposedUser) {
dbQuery {
Users.update({ Users.id eq id }) {
it[name] = user.name
it[age] = user.age
}
}
}
suspend fun delete(id: Int) {
dbQuery {
Users.deleteWhere { Users.id.eq(id) }
}
}
}
|
MyBook/app/src/androidTest/java/com/example/mybook/ExampleInstrumentedTest.kt | 2715868811 | package com.example.mybook
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.mybook", appContext.packageName)
}
} |
MyBook/app/src/test/java/com/example/mybook/ExampleUnitTest.kt | 3562550553 | package com.example.mybook
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)
}
} |
MyBook/app/src/main/java/com/example/mybook/MainActivity.kt | 246417588 | package com.example.mybook
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle
class MainActivity : AppCompatActivity() {
lateinit var pdfView: PDFView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
pdfView = findViewById(R.id.idPDFView)
pdfView.fromAsset("halallyk_kyssalary.pdf")
.scrollHandle(DefaultScrollHandle(this))
.load()
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Diff.kt | 644060744 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlin.jvm.JvmStatic
internal class Diff {
val operation: Int
val path: MutableList<Any>
val value: JsonElement
val toPath: List<Any> //only to be used in move operation
constructor(operation: Int, path: List<Any>, value: JsonElement) {
this.operation = operation
this.path = path.toMutableList()
this.toPath= listOf()
this.value = value
}
constructor(operation: Int, fromPath: List<Any>, toPath: List<Any>) {
this.operation = operation
this.path = fromPath.toMutableList()
this.toPath = toPath
this.value = JsonNull
}
companion object {
@JvmStatic
fun generateDiff(replace: Int, path: List<Any>, target: JsonElement): Diff {
return Diff(replace, path, target)
}
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonDiff.kt | 370692572 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.lcs.ListUtils
import kotlinx.serialization.json.*
import kotlin.jvm.JvmStatic
import kotlin.math.min
object JsonDiff {
internal var op = Operations()
internal var consts = Constants()
@JvmStatic
fun asJson(source: JsonElement, target: JsonElement): JsonArray {
val diffs = ArrayList<Diff>()
val path = ArrayList<Any>()
/*
* generating diffs in the order of their occurrence
*/
generateDiffs(diffs, path, source, target)
/*
* Merging remove & add to move operation
*/
compactDiffs(diffs)
/*
* Introduce copy operation
*/
introduceCopyOperation(source, target, diffs)
return getJsonNodes(diffs)
}
private fun getMatchingValuePath(unchangedValues: Map<JsonElement, List<Any>>, value: JsonElement): List<Any>? {
return unchangedValues[value]
}
private fun introduceCopyOperation(source: JsonElement, target: JsonElement, diffs: MutableList<Diff>) {
val unchangedValues = getUnchangedPart(source, target)
for (i in diffs.indices) {
val diff = diffs[i]
if (op.ADD==diff.operation) {
val matchingValuePath = getMatchingValuePath(unchangedValues, diff.value)
if (matchingValuePath != null) {
diffs[i] = Diff(op.COPY, matchingValuePath, diff.path)
}
}
}
}
private fun getUnchangedPart(source: JsonElement, target: JsonElement): Map<JsonElement, List<Any>> {
val unchangedValues = HashMap<JsonElement, List<Any>>()
computeUnchangedValues(unchangedValues, listOf(), source, target)
return unchangedValues
}
private fun computeUnchangedValues(unchangedValues: MutableMap<JsonElement, List<Any>>, path: List<Any>, source: JsonElement, target: JsonElement) {
if (source == target) {
unchangedValues.put(target, path)
return
}
val firstType = NodeType.getNodeType(source)
val secondType = NodeType.getNodeType(target)
if (firstType == secondType) {
when (firstType) {
NodeType.OBJECT -> computeObject(unchangedValues, path, source.jsonObject, target.jsonObject)
NodeType.ARRAY -> computeArray(unchangedValues, path, source.jsonArray, target.jsonArray)
}/* nothing */
}
}
private fun computeArray(unchangedValues: MutableMap<JsonElement, List<Any>>, path: List<Any>, source: JsonArray, target: JsonArray) {
val size = min(source.size, target.size)
for (i in 0..size - 1) {
val currPath = getPath(path, i)
computeUnchangedValues(unchangedValues, currPath, source.get(i), target.get(i))
}
}
private fun computeObject(unchangedValues: MutableMap<JsonElement, List<Any>>, path: List<Any>, source: JsonObject, target: JsonObject) {
//val firstFields = source.entrySet().iterator()
val firstFields = source.iterator()
while (firstFields.hasNext()) {
val name = firstFields.next().key
if (target.containsKey(name)) {
val currPath = getPath(path, name)
computeUnchangedValues(unchangedValues, currPath, source.get(name)!!, target.get(name)!!)
}
}
}
/**
* This method merge 2 diffs ( remove then add, or vice versa ) with same value into one Move operation,
* all the core logic resides here only
*/
private fun compactDiffs(diffs: MutableList<Diff>) {
var i=-1
while (++i <=diffs.size-1) {
val diff1 = diffs[i]
// if not remove OR add, move to next diff
if (!(op.REMOVE==diff1.operation || op.ADD==diff1.operation)) {
continue
}
for (j in i + 1..diffs.size - 1) {
val diff2 = diffs[j]
if (diff1.value != diff2.value) {
continue
}
var moveDiff: Diff? = null
if (op.REMOVE==diff1.operation && op.ADD==diff2.operation) {
computeRelativePath(diff2.path, i + 1, j - 1, diffs)
moveDiff = Diff(op.MOVE, diff1.path, diff2.path)
} else if (op.ADD==diff1.operation && op.REMOVE==diff2.operation) {
computeRelativePath(diff2.path, i, j - 1, diffs) // diff1's add should also be considered
moveDiff = Diff(op.MOVE, diff2.path, diff1.path)
}
if (moveDiff != null) {
diffs.removeAt(j)
diffs[i] = moveDiff
break
}
}
}
}
//Note : only to be used for arrays
//Finds the longest common Ancestor ending at Array
private fun computeRelativePath(path: MutableList<Any>, startIdx: Int, endIdx: Int, diffs: List<Diff>) {
val counters = ArrayList<Int>()
resetCounters(counters, path.size)
for (i in startIdx..endIdx) {
val diff = diffs[i]
//Adjust relative path according to #ADD and #Remove
if (op.ADD==diff.operation || op.REMOVE==diff.operation) {
updatePath(path, diff, counters)
}
}
updatePathWithCounters(counters, path)
}
private fun resetCounters(counters: MutableList<Int>, size: Int) {
for (i in 0..size - 1) {
counters.add(0)
}
}
private fun updatePathWithCounters(counters: List<Int>, path: MutableList<Any>) {
for (i in counters.indices) {
val value = counters[i]
if (value != 0) {
val currValue = path[i].toString().toInt()
path[i] = (currValue + value).toString()
}
}
}
private fun updatePath(path: List<Any>, pseudo: Diff, counters: MutableList<Int>) {
//find longest common prefix of both the paths
if (pseudo.path.size <= path.size) {
var idx = -1
for (i in 0..pseudo.path.size - 1 - 1) {
if (pseudo.path[i] == path[i]) {
idx = i
} else {
break
}
}
if (idx == pseudo.path.size - 2) {
if (pseudo.path[pseudo.path.size - 1] is Int) {
updateCounters(pseudo, pseudo.path.size - 1, counters)
}
}
}
}
private fun updateCounters(pseudo: Diff, idx: Int, counters: MutableList<Int>) {
if (op.ADD==pseudo.operation) {
counters[idx] = counters[idx] - 1
} else {
if (op.REMOVE==pseudo.operation) {
counters[idx] = counters[idx] + 1
}
}
}
private fun getJsonNodes(diffs: List<Diff>): JsonArray {
var patch = JsonArray(emptyList())
for (diff in diffs) {
val jsonNode = getJsonNode(diff)
patch = patch.add(jsonNode)
}
return patch
}
private fun getJsonNode(diff: Diff): JsonObject {
var jsonNode = JsonObject(emptyMap())
jsonNode = jsonNode.addProperty(consts.OP, op.nameFromOp(diff.operation))
if (op.MOVE==diff.operation || op.COPY==diff.operation) {
jsonNode = jsonNode.addProperty(consts.FROM, getArrayNodeRepresentation(diff.path)) //required {from} only in case of Move Operation
jsonNode = jsonNode.addProperty(consts.PATH, getArrayNodeRepresentation(diff.toPath)) // destination Path
} else {
jsonNode = jsonNode.addProperty(consts.PATH, getArrayNodeRepresentation(diff.path))
jsonNode = jsonNode.add(consts.VALUE, diff.value)
}
return jsonNode
}
private fun EncodePath(`object`: Any): String {
val path = `object`.toString() // see http://tools.ietf.org/html/rfc6901#section-4
return path.replace("~".toRegex(), "~0").replace("/".toRegex(), "~1")
}
//join path parts in argument 'path', inserting a '/' between joined elements, starting with '/' and transforming the element of the list with ENCODE_PATH_FUNCTION
private fun getArrayNodeRepresentation(path: List<Any>): String {
// return Joiner.on('/').appendTo(new StringBuilder().append('/'),
// Iterables.transform(path, ENCODE_PATH_FUNCTION)).toString();
val sb = StringBuilder()
for (i in path.indices) {
sb.append('/')
sb.append(EncodePath(path[i]))
}
return sb.toString()
}
private fun generateDiffs(diffs: MutableList<Diff>, path: List<Any>, source: JsonElement, target: JsonElement) {
if (source != target) {
val sourceType = NodeType.getNodeType(source)
val targetType = NodeType.getNodeType(target)
if (sourceType == NodeType.ARRAY && targetType == NodeType.ARRAY) {
//both are arrays
compareArray(diffs, path, source.jsonArray, target.jsonArray)
} else if (sourceType == NodeType.OBJECT && targetType == NodeType.OBJECT) {
//both are json
compareObjects(diffs, path, source.jsonObject, target.jsonObject)
} else {
//can be replaced
diffs.add(Diff.generateDiff(op.REPLACE, path, target))
}
}
}
private fun compareArray(diffs: MutableList<Diff>, path: List<Any>, source: JsonArray, target: JsonArray) {
val lcs = getLCS(source, target)
var srcIdx = 0
var targetIdx = 0
var lcsIdx = 0
val srcSize = source.size
val targetSize = target.size
val lcsSize = lcs.size
var pos = 0
while (lcsIdx < lcsSize) {
val lcsNode = lcs[lcsIdx]
val srcNode = source.get(srcIdx)
val targetNode = target.get(targetIdx)
if (lcsNode == srcNode && lcsNode == targetNode) { // Both are same as lcs node, nothing to do here
srcIdx++
targetIdx++
lcsIdx++
pos++
} else {
if (lcsNode == srcNode) { // src node is same as lcs, but not targetNode
//addition
val currPath = getPath(path, pos)
diffs.add(Diff.generateDiff(op.ADD, currPath, targetNode))
pos++
targetIdx++
} else if (lcsNode == targetNode) { //targetNode node is same as lcs, but not src
//removal,
val currPath = getPath(path, pos)
diffs.add(Diff.generateDiff(op.REMOVE, currPath, srcNode))
srcIdx++
} else {
val currPath = getPath(path, pos)
//both are unequal to lcs node
generateDiffs(diffs, currPath, srcNode, targetNode)
srcIdx++
targetIdx++
pos++
}
}
}
while (srcIdx < srcSize && targetIdx < targetSize) {
val srcNode = source.get(srcIdx)
val targetNode = target.get(targetIdx)
val currPath = getPath(path, pos)
generateDiffs(diffs, currPath, srcNode, targetNode)
srcIdx++
targetIdx++
pos++
}
pos = addRemaining(diffs, path, target, pos, targetIdx, targetSize)
removeRemaining(diffs, path, pos, srcIdx, srcSize, source)
}
private fun removeRemaining(diffs: MutableList<Diff>, path: List<Any>, pos: Int, srcIdx_: Int, srcSize: Int, source_: JsonElement): Int {
var srcIdx = srcIdx_
val source = source_.jsonArray
while (srcIdx < srcSize) {
val currPath = getPath(path, pos)
diffs.add(Diff.generateDiff(op.REMOVE, currPath, source.get(srcIdx)))
srcIdx++
}
return pos
}
private fun addRemaining(diffs: MutableList<Diff>, path: List<Any>, target_: JsonElement, pos_: Int, targetIdx_: Int, targetSize: Int): Int {
var pos = pos_
var targetIdx = targetIdx_
val target = target_.jsonArray
while (targetIdx < targetSize) {
val jsonNode = target.get(targetIdx)
val currPath = getPath(path, pos)
diffs.add(Diff.generateDiff(op.ADD, currPath, jsonNode.deepCopy()))
pos++
targetIdx++
}
return pos
}
private fun compareObjects(diffs: MutableList<Diff>, path: List<Any>, source: JsonObject, target: JsonObject) {
val keysFromSrc = source.iterator()
while (keysFromSrc.hasNext()) {
val key = keysFromSrc.next().key
if (!target.containsKey(key)) {
//remove case
val currPath = getPath(path, key)
diffs.add(Diff.generateDiff(op.REMOVE, currPath, source.get(key)!!))
continue
}
val currPath = getPath(path, key)
generateDiffs(diffs, currPath, source.get(key)!!, target.get(key)!!)
}
val keysFromTarget = target.iterator()
while (keysFromTarget.hasNext()) {
val key = keysFromTarget.next().key
if (!source.containsKey(key)) {
//add case
val currPath = getPath(path, key)
diffs.add(Diff.generateDiff(op.ADD, currPath, target.get(key)!!))
}
}
}
private fun getPath(path: List<Any>, key: Any): List<Any> {
val toReturn = ArrayList<Any>()
toReturn.addAll(path)
toReturn.add(key)
return toReturn
}
private fun getLCS(first_: JsonElement, second_: JsonElement): List<JsonElement> {
if (first_ !is JsonArray) throw IllegalArgumentException("LCS can only work on JSON arrays")
if (second_ !is JsonArray) throw IllegalArgumentException("LCS can only work on JSON arrays")
val first = first_ as JsonArray
val second = second_ as JsonArray
return ListUtils.longestCommonSubsequence(first.toList(),second.toList())
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Operations.kt | 2389617351 | package com.reidsync.kxjsonpatch
internal open class Operations {
val ADD: Int = 0
val REMOVE: Int = 1
val REPLACE: Int = 2
val MOVE: Int = 3
val COPY: Int = 4
val TEST: Int = 5
open val ADD_name = "add"
open val REMOVE_name = "remove"
open val REPLACE_name = "replace"
open val MOVE_name = "move"
open val COPY_name = "copy"
open val TEST_name = "test"
private val OPS = mapOf(
ADD_name to ADD,
REMOVE_name to REMOVE,
REPLACE_name to REPLACE,
MOVE_name to MOVE,
COPY_name to COPY,
TEST_name to TEST)
private val NAMES = mapOf(
ADD to ADD_name,
REMOVE to REMOVE_name,
REPLACE to REPLACE_name,
MOVE to MOVE_name,
COPY to COPY_name,
TEST to TEST_name)
fun opFromName(rfcName: String): Int {
val res=OPS.get(rfcName.toLowerCase())
if(res==null) throw InvalidJsonPatchException("unknown / unsupported operation $rfcName")
return res
}
fun nameFromOp(operation: Int): String {
val res= NAMES.get(operation)
if(res==null) throw InvalidJsonPatchException("unknown / unsupported operation $operation")
return res
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/Equator.kt | 396106922 | package com.reidsync.kxjsonpatch.lcs
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
* law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/ /**
* An equation function, which determines equality between objects of type T.
*
*
* It is the functional sibling of [java.util.Comparator]; [Equator] is to
* [Object] as [java.util.Comparator] is to [java.lang.Comparable].
*
* @param <T> the types of object this [Equator] can evaluate.
* @since 4.0
* @version $Id: Equator.java 1540567 2013-11-10 22:19:29Z tn $
</T> */
interface Equator<T> {
/**
* Evaluates the two arguments for their equality.
*
* @param o1 the first object to be equated.
* @param o2 the second object to be equated.
* @return whether the two objects are equal.
*/
fun equate(o1: T, o2: T): Boolean
/**
* Calculates the hash for the object, based on the method of equality used in the equate
* method. This is used for classes that delegate their [equals(Object)][Object.equals] method to an
* Equator (and so must also delegate their [hashCode()][Object.hashCode] method), or for implementations
* of org.apache.commons.collections4.map.HashedMap that use an Equator for the key objects.
*
* @param o the object to calculate the hash for.
* @return the hash of the object.
*/
fun hash(o: T): Int
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/EditScript.kt | 1524585298 | package com.reidsync.kxjsonpatch.lcs
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* This class gathers all the [commands][EditCommand] needed to transform
* one objects sequence into another objects sequence.
*
*
* An edit script is the most general view of the differences between two
* sequences. It is built as the result of the comparison between two sequences
* by the [SequencesComparator] class. The user can
* walk through it using the *visitor* design pattern.
*
*
* It is guaranteed that the objects embedded in the [insert][InsertCommand] come from the second sequence and that the objects embedded in
* either the [delete commands][DeleteCommand] or [keep][KeepCommand] come from the first sequence. This can be important if subclassing
* is used for some elements in the first sequence and the `equals`
* method is specialized.
*
* @see SequencesComparator
*
* @see EditCommand
*
* @see CommandVisitor
*
*
* @since 4.0
* @version $Id: EditScript.java 1477760 2013-04-30 18:34:03Z tn $
*/
class EditScript<T> {
/** Container for the commands. */
private val commands: MutableList<EditCommand<T>>
/**
* Get the length of the Longest Common Subsequence (LCS). The length of the
* longest common subsequence is the number of [keep][KeepCommand] in the script.
*
* @return length of the Longest Common Subsequence
*/
/** Length of the longest common subsequence. */
var lCSLength: Int
private set
/**
* Get the number of effective modifications. The number of effective
* modification is the number of [delete][DeleteCommand] and
* [insert][InsertCommand] commands in the script.
*
* @return number of effective modifications
*/
/** Number of modifications. */
var modifications: Int
private set
/**
* Simple constructor. Creates a new empty script.
*/
init {
commands = ArrayList<EditCommand<T>>()
lCSLength = 0
modifications = 0
}
/**
* Add a keep command to the script.
*
* @param command command to add
*/
fun append(command: KeepCommand<T>) {
commands.add(command)
++lCSLength
}
/**
* Add an insert command to the script.
*
* @param command command to add
*/
fun append(command: InsertCommand<T>) {
commands.add(command)
++modifications
}
/**
* Add a delete command to the script.
*
* @param command command to add
*/
fun append(command: DeleteCommand<T>) {
commands.add(command)
++modifications
}
/**
* Visit the script. The script implements the *visitor* design
* pattern, this method is the entry point to which the user supplies its
* own visitor, the script will be responsible to drive it through the
* commands in order and call the appropriate method as each command is
* encountered.
*
* @param visitor the visitor that will visit all commands in turn
*/
fun visit(visitor: CommandVisitor<T>) {
for (command in commands) {
command.accept(visitor)
}
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/SequencesComparator.kt | 2727382952 | package com.reidsync.kxjsonpatch.lcs
import kotlin.jvm.JvmOverloads
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class allows to compare two objects sequences.
*
*
* The two sequences can hold any object type, as only the `equals`
* method is used to compare the elements of the sequences. It is guaranteed
* that the comparisons will always be done as `o1.equals(o2)` where
* `o1` belongs to the first sequence and `o2` belongs to
* the second sequence. This can be important if subclassing is used for some
* elements in the first sequence and the `equals` method is
* specialized.
*
*
* Comparison can be seen from two points of view: either as giving the smallest
* modification allowing to transform the first sequence into the second one, or
* as giving the longest sequence which is a subsequence of both initial
* sequences. The `equals` method is used to compare objects, so any
* object can be put into sequences. Modifications include deleting, inserting
* or keeping one object, starting from the beginning of the first sequence.
*
*
* This class implements the comparison algorithm, which is the very efficient
* algorithm from Eugene W. Myers
* [
* An O(ND) Difference Algorithm and Its Variations](http://www.cis.upenn.edu/~bcpierce/courses/dd/papers/diff.ps). This algorithm produces
* the shortest possible
* [edit script][EditScript]
* containing all the
* [commands][EditCommand]
* needed to transform the first sequence into the second one.
*
* @see EditScript
*
* @see EditCommand
*
* @see CommandVisitor
*
*
* @since 4.0
* @version $Id: SequencesComparator.java 1540567 2013-11-10 22:19:29Z tn $
*/
class SequencesComparator<T> @JvmOverloads constructor(
//class SequencesComparator<T> constructor(
sequence1: List<T>,
sequence2: List<T>,
equator: Equator<in T> = DefaultEquator.defaultEquator()
) {
/** First sequence. */
private val sequence1: List<T>
/** Second sequence. */
private val sequence2: List<T>
/** The equator used for testing object equality. */
private val equator: Equator<in T>
/** Temporary variables. */
private val vDown: IntArray
private val vUp: IntArray
/**
* Simple constructor.
*
*
* Creates a new instance of SequencesComparator with a custom [Equator].
*
*
* It is *guaranteed* that the comparisons will always be done as
* `Equator.equate(o1, o2)` where `o1` belongs to the first
* sequence and `o2` belongs to the second sequence.
*
* @param sequence1 first sequence to be compared
* @param sequence2 second sequence to be compared
* @param equator the equator to use for testing object equality
*/
/**
* Simple constructor.
*
*
* Creates a new instance of SequencesComparator using a [DefaultEquator].
*
*
* It is *guaranteed* that the comparisons will always be done as
* `o1.equals(o2)` where `o1` belongs to the first
* sequence and `o2` belongs to the second sequence. This can be
* important if subclassing is used for some elements in the first sequence
* and the `equals` method is specialized.
*
* @param sequence1 first sequence to be compared
* @param sequence2 second sequence to be compared
*/
init {
this.sequence1 = sequence1
this.sequence2 = sequence2
this.equator = equator
val size = sequence1.size + sequence2.size + 2
vDown = IntArray(size)
vUp = IntArray(size)
}
/**
* Get the [EditScript] object.
*
*
* It is guaranteed that the objects embedded in the [ insert commands][InsertCommand] come from the second sequence and that the objects
* embedded in either the [delete commands][DeleteCommand] or
* [keep commands][KeepCommand] come from the first sequence. This can
* be important if subclassing is used for some elements in the first
* sequence and the `equals` method is specialized.
*
* @return the edit script resulting from the comparison of the two
* sequences
*/
fun getScript(): EditScript<T> {
val script = EditScript<T>()
buildScript(0, sequence1.size, 0, sequence2.size, script)
return script
}
/**
* Build a snake.
*
* @param start the value of the start of the snake
* @param diag the value of the diagonal of the snake
* @param end1 the value of the end of the first sequence to be compared
* @param end2 the value of the end of the second sequence to be compared
* @return the snake built
*/
private fun buildSnake(start: Int, diag: Int, end1: Int, end2: Int): Snake {
var end = start
while (end - diag < end2 && end < end1 && equator.equate(
sequence1[end],
sequence2[end - diag]
)
) {
++end
}
return Snake(start, end, diag)
}
/**
* Get the middle snake corresponding to two subsequences of the
* main sequences.
*
*
* The snake is found using the MYERS Algorithm (this algorithms has
* also been implemented in the GNU diff program). This algorithm is
* explained in Eugene Myers article:
* [
* An O(ND) Difference Algorithm and Its Variations](http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps).
*
* @param start1 the begin of the first sequence to be compared
* @param end1 the end of the first sequence to be compared
* @param start2 the begin of the second sequence to be compared
* @param end2 the end of the second sequence to be compared
* @return the middle snake
*/
private fun getMiddleSnake(start1: Int, end1: Int, start2: Int, end2: Int): Snake? {
// Myers Algorithm
// Initialisations
val m = end1 - start1
val n = end2 - start2
if (m == 0 || n == 0) {
return null
}
val delta = m - n
val sum = n + m
val offset = (if (sum % 2 == 0) sum else sum + 1) / 2
vDown[1 + offset] = start1
vUp[1 + offset] = end1 + 1
for (d in 0..offset) {
// Down
run {
var k = -d
while (k <= d) {
// First step
val i = k + offset
if (k == -d || k != d && vDown[i - 1] < vDown[i + 1]) {
vDown[i] = vDown[i + 1]
} else {
vDown[i] = vDown[i - 1] + 1
}
var x = vDown[i]
var y = x - start1 + start2 - k
while (x < end1 && y < end2 && equator.equate(
sequence1[x],
sequence2[y]
)
) {
vDown[i] = ++x
++y
}
// Second step
if (delta % 2 != 0 && delta - d <= k && k <= delta + d) {
if (vUp[i - delta] <= vDown[i]) {
return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2)
}
}
k += 2
}
}
// Up
var k = delta - d
while (k <= delta + d) {
// First step
val i = k + offset - delta
if (k == delta - d
|| k != delta + d && vUp[i + 1] <= vUp[i - 1]
) {
vUp[i] = vUp[i + 1] - 1
} else {
vUp[i] = vUp[i - 1]
}
var x = vUp[i] - 1
var y = x - start1 + start2 - k
while (x >= start1 && y >= start2 && equator.equate(sequence1[x], sequence2[y])) {
vUp[i] = x--
y--
}
// Second step
if (delta % 2 == 0 && -d <= k && k <= d) {
if (vUp[i] <= vDown[i + delta]) {
return buildSnake(vUp[i], k + start1 - start2, end1, end2)
}
}
k += 2
}
}
throw RuntimeException("Internal Error")
}
/**
* Build an edit script.
*
* @param start1 the begin of the first sequence to be compared
* @param end1 the end of the first sequence to be compared
* @param start2 the begin of the second sequence to be compared
* @param end2 the end of the second sequence to be compared
* @param script the edited script
*/
private fun buildScript(
start1: Int, end1: Int, start2: Int, end2: Int,
script: EditScript<T>
) {
val middle = getMiddleSnake(start1, end1, start2, end2)
if (middle == null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
var i = start1
var j = start2
while (i < end1 || j < end2) {
if (i < end1 && j < end2 && equator.equate(sequence1[i], sequence2[j])) {
script.append(KeepCommand(sequence1[i]))
++i
++j
} else {
if (end1 - start1 > end2 - start2) {
script.append(DeleteCommand(sequence1[i]))
++i
} else {
script.append(InsertCommand(sequence2[j]))
++j
}
}
}
} else {
buildScript(
start1, middle.start,
start2, middle.start - middle.diag,
script
)
for (i in middle.start until middle.end) {
script.append(KeepCommand(sequence1[i]))
}
buildScript(
middle.end, end1,
middle.end - middle.diag, end2,
script
)
}
}
/**
* This class is a simple placeholder to hold the end part of a path
* under construction in a [SequencesComparator].
*/
private class Snake
/**
* Simple constructor. Creates a new instance of Snake with specified indices.
*
* @param start start index of the snake
* @param end end index of the snake
* @param diag diagonal number
*/(
/** Start index. */
val start: Int,
/** End index. */
val end: Int,
/** Diagonal number. */
val diag: Int
) {
/**
* Get the start index of the snake.
*
* @return start index of the snake
*/
/**
* Get the end index of the snake.
*
* @return end index of the snake
*/
/**
* Get the diagonal number of the snake.
*
* @return diagonal number of the snake
*/
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/DefaultEquator.kt | 2692115764 | package com.reidsync.kxjsonpatch.lcs
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Default [Equator] implementation.
*
* @param <T> the types of object this [Equator] can evaluate.
* @since 4.0
* @version $Id: DefaultEquator.java 1543950 2013-11-20 21:13:35Z tn $
</T> */
class DefaultEquator<T>
/**
* Restricted constructor.
*/
private constructor() : Equator<T> {
/**
* {@inheritDoc} Delegates to [Object.equals].
*/
override fun equate(o1: T, o2: T): Boolean {
return o1 === o2 || o1 != null && o1 == o2
}
/**
* {@inheritDoc}
*
* @return `o.hashCode()` if `o` is non-
* `null`, else [.HASHCODE_NULL].
*/
override fun hash(o: T): Int {
return o?.hashCode() ?: HASHCODE_NULL
}
private fun readResolve(): Any {
return INSTANCE
}
companion object {
/** Serial version UID */
private const val serialVersionUID = 825802648423525485L
/** Static instance */
// the static instance works for all types
val INSTANCE: DefaultEquator<*> = DefaultEquator<Any>()
/**
* Hashcode used for `null` objects.
*/
const val HASHCODE_NULL = -1
/**
* Factory returning the typed singleton instance.
*
* @param <T> the object type
* @return the singleton instance
</T> */
// the static instance works for all types
fun <T> defaultEquator(): DefaultEquator<T> {
return INSTANCE as DefaultEquator<T>
}
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/DeleteCommand.kt | 489849456 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch.lcs
/**
* Command representing the deletion of one object of the first sequence.
*
*
* When one object of the first sequence has no corresponding object in the
* second sequence at the right place, the [edit script][EditScript]
* transforming the first sequence into the second sequence uses an instance of
* this class to represent the deletion of this object. The objects embedded in
* these type of commands always come from the first sequence.
*
* @see SequencesComparator
*
* @see EditScript
*
*
* @since 4.0
* @version $Id: DeleteCommand.java 1477760 2013-04-30 18:34:03Z tn $
*/
class DeleteCommand<T>
/**
* Simple constructor. Creates a new instance of [DeleteCommand].
*
* @param object the object of the first sequence that should be deleted
*/
(`object`: T) : EditCommand<T>(`object`) {
/**
* Accept a visitor. When a `DeleteCommand` accepts a visitor, it calls
* its [visitDeleteCommand][CommandVisitor.visitDeleteCommand] method.
*
* @param visitor the visitor to be accepted
*/
override fun accept(visitor: CommandVisitor<T>?) {
visitor?.visitDeleteCommand(`object`)
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/ListUtils.kt | 3082552515 | package com.reidsync.kxjsonpatch.lcs
/**
* code extracted from Apache Commons Collections 4.1
* Created by daely on 7/22/2016.
*/
object ListUtils {
//-----------------------------------------------------------------------
/**
* Returns the longest common subsequence (LCS) of two sequences (lists).
*
* @param <E> the element type
* @param a the first list
* @param b the second list
* @return the longest common subsequence
* @throws NullPointerException if either list is `null`
* @since 4.0
</E> */
fun <E> longestCommonSubsequence(a: List<E>?, b: List<E>?): List<E> {
return longestCommonSubsequence(a, b, DefaultEquator.defaultEquator())
}
/**
* Returns the longest common subsequence (LCS) of two sequences (lists).
*
* @param <E> the element type
* @param a the first list
* @param b the second list
* @param equator the equator used to test object equality
* @return the longest common subsequence
* @throws NullPointerException if either list or the equator is `null`
* @since 4.0
</E> */
fun <E> longestCommonSubsequence(
a: List<E>?, b: List<E>?,
equator: Equator<in E>?
): List<E> {
if (a == null || b == null) {
throw NullPointerException("List must not be null")
}
if (equator == null) {
throw NullPointerException("Equator must not be null")
}
val comparator: SequencesComparator<E> =
SequencesComparator<E>(a, b, equator)
val script: EditScript<E> = comparator.getScript()
val visitor = LcsVisitor<E>()
script.visit(visitor)
return visitor.subSequence
}
/**
* A helper class used to construct the longest common subsequence.
*/
private class LcsVisitor<E> : CommandVisitor<E> {
private val sequence: ArrayList<E>
init {
sequence = ArrayList<E>()
}
override fun visitInsertCommand(`object`: E) {}
override fun visitDeleteCommand(`object`: E) {}
override fun visitKeepCommand(`object`: E) {
sequence.add(`object`)
}
val subSequence: List<E>
get() = sequence
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/KeepCommand.kt | 1649252788 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch.lcs
/**
* Command representing the keeping of one object present in both sequences.
*
*
* When one object of the first sequence `equals` another objects in
* the second sequence at the right place, the [edit script][EditScript]
* transforming the first sequence into the second sequence uses an instance of
* this class to represent the keeping of this object. The objects embedded in
* these type of commands always come from the first sequence.
*
* @see SequencesComparator
*
* @see EditScript
*
*
* @since 4.0
* @version $Id: KeepCommand.java 1477760 2013-04-30 18:34:03Z tn $
*/
class KeepCommand<T>
/**
* Simple constructor. Creates a new instance of KeepCommand
*
* @param object the object belonging to both sequences (the object is a
* reference to the instance in the first sequence which is known
* to be equal to an instance in the second sequence)
*/
(`object`: T) : EditCommand<T>(`object`) {
/**
* Accept a visitor. When a `KeepCommand` accepts a visitor, it
* calls its [visitKeepCommand][CommandVisitor.visitKeepCommand] method.
*
* @param visitor the visitor to be accepted
*/
override fun accept(visitor: CommandVisitor<T>?) {
visitor?.visitKeepCommand(`object`)
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/EditCommand.kt | 2076046877 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch.lcs
/**
* Abstract base class for all commands used to transform an objects sequence
* into another one.
*
*
* When two objects sequences are compared through the
* [SequencesComparator.getScript] method,
* the result is provided has a [script][EditScript] containing the commands
* that progressively transform the first sequence into the second one.
*
*
* There are only three types of commands, all of which are subclasses of this
* abstract class. Each command is associated with one object belonging to at
* least one of the sequences. These commands are [ InsertCommand][InsertCommand] which correspond to an object of the second sequence being
* inserted into the first sequence, [DeleteCommand] which
* correspond to an object of the first sequence being removed and
* [KeepCommand] which correspond to an object of the first
* sequence which `equals` an object in the second sequence. It is
* guaranteed that comparison is always performed this way (i.e. the
* `equals` method of the object from the first sequence is used and
* the object passed as an argument comes from the second sequence) ; this can
* be important if subclassing is used for some elements in the first sequence
* and the `equals` method is specialized.
*
* @see SequencesComparator
*
* @see EditScript
*
*
* @since 4.0
* @version $Id: EditCommand.java 1477760 2013-04-30 18:34:03Z tn $
*/
abstract class EditCommand<T>
/**
* Simple constructor. Creates a new instance of EditCommand
*
* @param object reference to the object associated with this command, this
* refers to an element of one of the sequences being compared
*/ protected constructor(
/** Object on which the command should be applied. */
protected val `object`: T
) {
/**
* Returns the object associated with this command.
*
* @return the object on which the command is applied
*/
/**
* Accept a visitor.
*
*
* This method is invoked for each commands belonging to
* an [EditScript], in order to implement the visitor design pattern
*
* @param visitor the visitor to be accepted
*/
abstract fun accept(visitor: CommandVisitor<T>?)
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/CommandVisitor.kt | 3046462889 | package com.reidsync.kxjsonpatch.lcs
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This interface should be implemented by user object to walk
* through [EditScript] objects.
*
*
* Users should implement this interface in order to walk through
* the [EditScript] object created by the comparison
* of two sequences. This is a direct application of the visitor
* design pattern. The [EditScript.visit]
* method takes an object implementing this interface as an argument,
* it will perform the loop over all commands in the script and the
* proper methods of the user class will be called as the commands are
* encountered.
*
*
* The implementation of the user visitor class will depend on the
* need. Here are two examples.
*
*
* The first example is a visitor that build the longest common
* subsequence:
* <pre>
* import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
*
* import java.util.ArrayList;
*
* public class LongestCommonSubSequence implements CommandVisitor {
*
* public LongestCommonSubSequence() {
* a = new ArrayList();
* }
*
* public void visitInsertCommand(Object object) {
* }
*
* public void visitKeepCommand(Object object) {
* a.add(object);
* }
*
* public void visitDeleteCommand(Object object) {
* }
*
* public Object[] getSubSequence() {
* return a.toArray();
* }
*
* private ArrayList a;
*
* }
</pre> *
*
*
* The second example is a visitor that shows the commands and the way
* they transform the first sequence into the second one:
* <pre>
* import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
*
* import java.util.Arrays;
* import java.util.ArrayList;
* import java.util.Iterator;
*
* public class ShowVisitor implements CommandVisitor {
*
* public ShowVisitor(Object[] sequence1) {
* v = new ArrayList();
* v.addAll(Arrays.asList(sequence1));
* index = 0;
* }
*
* public void visitInsertCommand(Object object) {
* v.insertElementAt(object, index++);
* display("insert", object);
* }
*
* public void visitKeepCommand(Object object) {
* ++index;
* display("keep ", object);
* }
*
* public void visitDeleteCommand(Object object) {
* v.remove(index);
* display("delete", object);
* }
*
* private void display(String commandName, Object object) {
* System.out.println(commandName + " " + object + " ->" + this);
* }
*
* public String toString() {
* StringBuffer buffer = new StringBuffer();
* for (Iterator iter = v.iterator(); iter.hasNext();) {
* buffer.append(' ').append(iter.next());
* }
* return buffer.toString();
* }
*
* private ArrayList v;
* private int index;
*
* }
</pre> *
*
* @since 4.0
* @version $Id: CommandVisitor.java 1477760 2013-04-30 18:34:03Z tn $
*/
interface CommandVisitor<T> {
/**
* Method called when an insert command is encountered.
*
* @param object object to insert (this object comes from the second sequence)
*/
fun visitInsertCommand(`object`: T)
/**
* Method called when a keep command is encountered.
*
* @param object object to keep (this object comes from the first sequence)
*/
fun visitKeepCommand(`object`: T)
/**
* Method called when a delete command is encountered.
*
* @param object object to delete (this object comes from the first sequence)
*/
fun visitDeleteCommand(`object`: T)
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/InsertCommand.kt | 803684832 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch.lcs
/**
* Command representing the insertion of one object of the second sequence.
*
*
* When one object of the second sequence has no corresponding object in the
* first sequence at the right place, the [edit script][EditScript]
* transforming the first sequence into the second sequence uses an instance of
* this class to represent the insertion of this object. The objects embedded in
* these type of commands always come from the second sequence.
*
* @see SequencesComparator
*
* @see EditScript
*
*
* @since 4.0
* @version $Id: InsertCommand.java 1477760 2013-04-30 18:34:03Z tn $
*/
class InsertCommand<T>
/**
* Simple constructor. Creates a new instance of InsertCommand
*
* @param object the object of the second sequence that should be inserted
*/
(`object`: T) : EditCommand<T>(`object`) {
/**
* Accept a visitor. When an `InsertCommand` accepts a visitor,
* it calls its [visitInsertCommand][CommandVisitor.visitInsertCommand]
* method.
*
* @param visitor the visitor to be accepted
*/
override fun accept(visitor: CommandVisitor<T>?) {
visitor?.visitInsertCommand(`object`)
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/NodeType.kt | 1939966064 | package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.*
internal object NodeType {
val ARRAY = 1
val OBJECT = 2
// static final int NULL=3;
val PRIMITIVE_OR_NULL = 3
fun getNodeType(node: JsonElement): Int {
if (node is JsonArray) return ARRAY
if (node is JsonObject) return OBJECT
// if(node.isJsonNull()) return NULL;
return PRIMITIVE_OR_NULL
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchApplicationException.kt | 616163586 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
/**
* User: holograph
* Date: 03/08/16
*/
open class JsonPatchApplicationException : RuntimeException {
constructor(message: String) : super(message) {}
constructor(message: String, cause: Throwable) : super(message, cause) {}
constructor(cause: Throwable) : super(cause) {}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/NoopProcessor.kt | 2823232532 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.JsonElement
/** A JSON patch processor that does nothing, intended for testing and validation. */
class NoopProcessor : JsonPatchApplyProcessor() {
companion object {
val INSTANCE: NoopProcessor = NoopProcessor()
}
}
class JsonPatchEditingContextTestImpl(var source: JsonElement): JsonPatchEditingContext {
override fun remove(path: List<String>) {}
override fun replace(path: List<String>, value: JsonElement) {}
override fun add(path: List<String>, value: JsonElement) {}
override fun move(fromPath: List<String>, toPath: List<String>) {}
override fun copy(fromPath: List<String>, toPath: List<String>) {}
override fun test(path: List<String>, value: JsonElement) {}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/InvalidJsonPatchException.kt | 2004071684 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
/**
* User: holograph
* Date: 03/08/16
*/
class InvalidJsonPatchException : JsonPatchApplicationException {
constructor(message: String) : super(message) {}
constructor(message: String, cause: Throwable) : super(message, cause) {}
constructor(cause: Throwable) : super(cause) {}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchProcessor.kt | 505105408 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch;
import kotlinx.serialization.json.*
interface JsonPatchProcessor {
fun remove(path: List<String>)
fun replace(path: List<String>, value: JsonElement)
fun add(path: List<String>, value: JsonElement)
fun move(fromPath: List<String>, toPath: List<String>)
fun copy(fromPath: List<String>, toPath: List<String>)
fun test(path: List<String>, value: JsonElement)
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchApplyProcessor.kt | 1821859254 | package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
/*
* Copyright 2023 Reid Byun.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
abstract class JsonPatchApplyProcessor(private val source: JsonElement = JsonNull) {
var targetSource: JsonElement = source
private set
open fun setSource(changedSource: JsonElement) {
targetSource = changedSource
}
}
//
//fun JsonPatchApplyProcessor.edit(actions: JsonPatchEditingContext.()->Unit) {
// val context = JsonPatchEditingContextImpl(source = this.targetSource)
// context.actions()
//
// this.setSource(context.source)
//}
fun JsonPatchApplyProcessor.edit(actions: JsonPatchEditingContext.()->Unit) {
if (this is NoopProcessor) { // for test
val context = JsonPatchEditingContextTestImpl(source = this.targetSource)
context.actions()
this.setSource(context.source)
}
else {
val context = JsonPatchEditingContextImpl(source = this.targetSource)
context.actions()
this.setSource(context.source)
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/ApplyProcessor.kt | 499412203 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.*
class ApplyProcessor(private val target: JsonElement) : JsonPatchApplyProcessor(target.deepCopy()) {
fun result(): JsonElement = targetSource
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatch.kt | 1318496332 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.*
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
object JsonPatch {
internal var op = Operations()
internal var consts = Constants()
private fun getPatchAttr(jsonNode: JsonObject, attr: String): JsonElement {
val child = jsonNode.get(attr) ?: throw InvalidJsonPatchException("Invalid JSON Patch payload (missing '$attr' field)")
return child
}
private fun getPatchAttrWithDefault(jsonNode: JsonObject, attr: String, defaultValue: JsonElement): JsonElement {
val child = jsonNode.get(attr)
if (child == null)
return defaultValue
else
return child
}
@Throws(InvalidJsonPatchException::class)
private fun process(patch: JsonElement, processor: JsonPatchApplyProcessor, flags: Set<CompatibilityFlags>) {
if (patch !is JsonArray)
throw InvalidJsonPatchException("Invalid JSON Patch payload (not an array)")
val operations = patch.jsonArray.iterator()
while (operations.hasNext()) {
val jsonNode_ = operations.next()
if (jsonNode_ !is JsonObject) throw InvalidJsonPatchException("Invalid JSON Patch payload (not an object)")
val jsonNode = jsonNode_.jsonObject
val operation = op.opFromName(getPatchAttr(jsonNode.jsonObject, consts.OP).toString().replace("\"".toRegex(), ""))
val path = getPath(getPatchAttr(jsonNode, consts.PATH))
when (operation) {
op.REMOVE -> {
processor.edit { remove(path) }
}
op.ADD -> {
val value: JsonElement
if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS))
value = getPatchAttr(jsonNode, consts.VALUE)
else
value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull)
processor.edit { add(path, value) }
}
op.REPLACE -> {
val value: JsonElement
if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS))
value = getPatchAttr(jsonNode, consts.VALUE)
else
value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull)
processor.edit { replace(path, value) }
}
op.MOVE -> {
val fromPath = getPath(getPatchAttr(jsonNode, consts.FROM))
processor.edit { move(fromPath, path) }
}
op.COPY -> {
val fromPath = getPath(getPatchAttr(jsonNode, consts.FROM))
processor.edit { copy(fromPath, path) }
}
op.TEST -> {
val value: JsonElement
if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS))
value = getPatchAttr(jsonNode, consts.VALUE)
else
value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull)
processor.edit { test(path, value) }
}
}
}
}
@Throws(InvalidJsonPatchException::class)
@JvmStatic
@JvmOverloads
fun validate(patch: JsonElement, flags: Set<CompatibilityFlags> = CompatibilityFlags.defaults()) {
process(patch, NoopProcessor.INSTANCE, flags)
}
@Throws(JsonPatchApplicationException::class)
@JvmStatic
@JvmOverloads
fun apply(patch: JsonElement, source: JsonElement, flags: Set<CompatibilityFlags> = CompatibilityFlags.defaults()): JsonElement {
val processor = ApplyProcessor(source)
process(patch, processor, flags)
return processor.result()
}
private fun decodePath(path: String): String {
return path.replace("~1".toRegex(), "/").replace("~0".toRegex(), "~") // see http://tools.ietf.org/html/rfc6901#section-4
}
private fun getPath(path: JsonElement): List<String> {
// List<String> paths = Splitter.on('/').splitToList(path.toString().replaceAll("\"", ""));
// return Lists.newArrayList(Iterables.transform(paths, DECODE_PATH_FUNCTION));
val pathstr = path.toString().replace("\"", "")
val paths = pathstr.split("/")
return paths.map { decodePath(it) }
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchEditingContextImpl.kt | 1323217581 | package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.*
/*
* Copyright 2023 Reid Byun.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class JsonPatchEditingContextImpl(var source: JsonElement): JsonPatchEditingContext {
override fun remove(path: List<String>) {
source = editElement(source, path, action = { root ->
if (path.isEmpty()) {
throw JsonPatchApplicationException("[Remove Operation] path is empty")
}
else {
var parentNode = root//getParentNode(root, searchPath)
if (parentNode == null) {
throw JsonPatchApplicationException("[Remove Operation] noSuchPath in source, path provided : " + path)
}
else {
val fieldToRemove = path[path.size - 1].replace("\"".toRegex(), "")
if (parentNode is JsonObject) {
val copyp = parentNode.remove(fieldToRemove)
println(parentNode)
println(copyp)
println(root)
parentNode = copyp
}
else if (parentNode is JsonArray) {
parentNode = parentNode.remove(arrayIndex(fieldToRemove, parentNode.size - 1))
//return parentNode
}
else {
throw JsonPatchApplicationException("[Remove Operation] noSuchPath in source, path provided : " + path)
}
}
parentNode
}}) ?: source
}
override fun replace(path: List<String>, value: JsonElement) {
source = editElement(source, path, action = { root ->
if (path.isEmpty()) {
throw JsonPatchApplicationException("[Replace Operation] path is empty")
} else {
var parentNode = getParentNode(source, path)
if (parentNode == null) {
throw JsonPatchApplicationException("[Replace Operation] noSuchPath in source, path provided : " + path)
} else {
val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "")
if (fieldToReplace.isEmpty() && path.size == 1) {
parentNode = value
}
else if (parentNode is JsonObject) {
parentNode = parentNode.add(fieldToReplace, value)
}
else if (parentNode is JsonArray) {
parentNode = parentNode.set(arrayIndex(fieldToReplace, parentNode.size - 1), value)
}
else {
throw JsonPatchApplicationException("[Replace Operation] noSuchPath in source, path provided : " + path)
}
parentNode
}
}
}) ?: source
}
override fun add(path: List<String>, value: JsonElement) {
source = editElement(source, path, action = { root ->
if (path.isEmpty()) {
throw JsonPatchApplicationException("[ADD Operation] path is empty , path : ")
} else {
var parentNode = root//getParentNode(root, searchPath)
if (parentNode == null) {
throw JsonPatchApplicationException("[ADD Operation] noSuchPath in source, path provided : " + path)
} else {
val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "")
if (fieldToReplace == "" && path.size == 1)
parentNode = value
else if (!parentNode.isContainerNode()) {
throw JsonPatchApplicationException("[ADD Operation] parent is not a container in source, path provided : $path | node : $parentNode")
}
else if (parentNode is JsonArray) {
parentNode = addToArray(path, value, parentNode)
}
else {
parentNode = addToObject(path, parentNode, value)
}
}
parentNode
}
}) ?: source
}
override fun move(fromPath: List<String>, toPath: List<String>) {
val parentNode = getParentNode(source, fromPath)
val field = fromPath[fromPath.size - 1].replace("\"".toRegex(), "")
val valueNode = if (parentNode!! is JsonArray) {
parentNode.jsonArray[field.toInt()]
}
else {
parentNode.jsonObject[field]
}
remove(fromPath)
add(toPath, valueNode!!)
}
override fun copy(fromPath: List<String>, toPath: List<String>) {
val parentNode = getParentNode(source, fromPath)
val field = fromPath[fromPath.size - 1].replace("\"".toRegex(), "")
val valueNode = if (parentNode!! is JsonArray) {
parentNode.jsonArray[field.toInt()]
}
else {
parentNode.jsonObject[field]
}
add(toPath, valueNode!!)
}
override fun test(path: List<String>, value: JsonElement) {
source = editElement(source, path, action = { root ->
if (path.isEmpty()) {
throw JsonPatchApplicationException("[TEST Operation] path is empty , path : ")
} else {
var parentNode = root
if (parentNode == null) {
throw JsonPatchApplicationException("[TEST Operation] noSuchPath in source, path provided : " + path)
}
else {
val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "")
if (fieldToReplace == "" && path.size == 1)
parentNode = value
else if (!parentNode.isContainerNode())
throw JsonPatchApplicationException("[TEST Operation] parent is not a container in source, path provided : $path | node : $parentNode")
else if (parentNode is JsonArray) {
val target = parentNode
val idxStr = path[path.size - 1]
if ("-" == idxStr) {
// see http://tools.ietf.org/html/rfc6902#section-4.1
if (target.get(target.size - 1) != value) {
throw JsonPatchApplicationException("[TEST Operation] value mismatch")
}
} else {
val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size)
if (target.get(idx) != value) {
throw JsonPatchApplicationException("[TEST Operation] value mismatch")
}
}
} else {
val target = parentNode as JsonObject
val key = path[path.size - 1].replace("\"".toRegex(), "")
if (target.get(key) != value) {
throw JsonPatchApplicationException("[TEST Operation] value mismatch")
}
}
parentNode
}
}
}) ?: source
}
private fun getParentNode(source: JsonElement, fromPath: List<String>): JsonElement? {
val pathToParent = fromPath.subList(0, fromPath.size - 1) // would never by out of bound, lets see
return getNode(source, pathToParent, 1)
}
private fun getNode(ret: JsonElement, path: List<String>, pos_: Int): JsonElement? {
var pos = pos_
if (pos >= path.size) {
return ret
}
val key = path[pos]
if (ret is JsonArray) {
val keyInt = (key.replace("\"".toRegex(), "")).toInt()
return getNode(ret[keyInt], path, ++pos)
} else if (ret is JsonObject) {
if (ret.containsKey(key)) {
return getNode(ret[key]!!, path, ++pos)
}
return null
} else {
return ret
}
}
private fun editElement(source: JsonElement, fromPath: List<String>, action: (JsonElement)-> JsonElement?): JsonElement? {
val pathToParent = fromPath.subList(0, fromPath.size - 1) // would never by out of bound, lets see
return findAndAction(source, pathToParent, 1, action)
}
private fun findAndAction(ret: JsonElement, path: List<String>, pos_: Int, action: (JsonElement)-> JsonElement?): JsonElement? {
var pos = pos_
if (pos >= path.size) {
// Result
return action(ret)
}
val key = path[pos]
if (ret is JsonArray) {
val keyInt = (key.replace("\"".toRegex(), "")).toInt()
return ret.set(keyInt, findAndAction(ret[keyInt], path, ++pos, action))
}
else if (ret is JsonObject) {
if (ret.containsKey(key)) {
return ret.set(key, findAndAction(ret[key]!!, path, ++pos, action))
}
return null
} else {
// Result
return action(ret)
}
}
private fun arrayIndex(s: String, max: Int): Int {
val index = s.toInt()
if (index < 0) {
throw JsonPatchApplicationException("index Out of bound, index is negative")
} else if (index > max) {
throw JsonPatchApplicationException("index Out of bound, index is greater than " + max)
}
return index
}
private fun addToObject(path: List<String>, node: JsonElement, value: JsonElement): JsonObject {
val target = node as JsonObject
val key = path[path.size - 1].replace("\"".toRegex(), "")
return target.add(key, value)
}
private fun addToArray(path: List<String>, value: JsonElement, parentNode: JsonElement): JsonElement {
var target = parentNode as JsonArray
val idxStr = path[path.size - 1]
if ("-" == idxStr) {
// see http://tools.ietf.org/html/rfc6902#section-4.1
//target.add(value)
target = target.add(value)
} else {
//val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size())
val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size)
target = target.insert(idx, value)
}
return target
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonElementExtensions.kt | 3052702610 | package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.*
/*
* Copyright 2023 Reid Byun.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* JsonElement Extensions
* */
fun JsonElement.apply(patch: JsonElement): JsonElement {
return JsonPatch.apply(patch, this)
}
fun JsonElement.generatePatch(with: JsonElement): JsonElement {
return JsonDiff.asJson(this, with)
}
internal fun JsonElement.isContainerNode(): Boolean {
return this is JsonArray || this is JsonObject
}
internal fun JsonElement.deepCopy(): JsonElement {
return when(this) {
is JsonArray -> this.jsonArray.copy {}
is JsonObject -> this.jsonObject.copy {}
is JsonNull -> JsonNull // An order of checking type between JsonNull and JsonPrimitive makes difference.
is JsonPrimitive -> this /* Todo check */
else -> this /* Todo check */
}
}
/*
* JsonArray Extensions
* */
internal fun JsonArray.add(value_: JsonElement?): JsonArray {
val value=value_ ?: JsonNull
return copy { add(value) }
}
internal fun JsonArray.insert(index: Int, value_: JsonElement?): JsonArray {
val value=value_ ?: JsonNull
return if(index>=size) {
this.add(value)
}
else if(index<0) {
this.copy { add(0, value)}
}
else {
this.copy { add(index, value) }
}
}
internal fun JsonArray.set(index: Int, value_: JsonElement?): JsonArray {
val value=value_ ?: JsonNull
if(index>=size) {
throw IndexOutOfBoundsException("")
}
return copy { this[index] = value }
}
internal fun JsonArray.remove(index:Int): JsonArray {
return copy { removeAt(index) }
}
private inline fun JsonArray.copy(mutatorBlock: MutableList<JsonElement>.() -> Unit): JsonArray {
return JsonArray(this.toMutableList().apply(mutatorBlock))
}
/*
* JsonObject Extensions
* */
internal fun JsonObject.add(key: String, value_: JsonElement?): JsonObject {
val value=value_ ?: JsonNull
return copy {
this[key] = value
}
}
internal fun JsonObject.remove(key: String): JsonObject {
return copy { remove(key) }
}
internal fun JsonObject.set(key: String, value_: JsonElement?): JsonObject {
val value=value_ ?: JsonNull
if(!this.containsKey(key)) {
throw IndexOutOfBoundsException("Key[$key] doesn't exist")
}
return copy {
this[key] = value
}
}
internal fun JsonObject.addProperty(key: String, value: String): JsonObject {
return this.copy {
this[key] = JsonPrimitive(value)
}
}
internal fun JsonObject.addProperty(key: String, value: Number): JsonObject {
return this.copy {
this[key] = JsonPrimitive(value)
}
}
private inline fun JsonObject.copy(mutatorBlock: MutableMap<String, JsonElement>.() -> Unit): JsonObject {
return JsonObject(this.toMutableMap().apply(mutatorBlock))
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/CompatibilityFlags.kt | 4148616520 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
/**
* Created by tomerga on 04/09/2016.
*/
enum class CompatibilityFlags {
MISSING_VALUES_AS_NULLS;
companion object {
fun defaults(): Set<CompatibilityFlags> {
return setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS)
}
}
}
|
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchEditingContext.kt | 2379248490 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch;
import kotlinx.serialization.json.*
interface JsonPatchEditingContext {
fun remove(path: List<String>)
fun replace(path: List<String>, value: JsonElement)
fun add(path: List<String>, value: JsonElement)
fun move(fromPath: List<String>, toPath: List<String>)
fun copy(fromPath: List<String>, toPath: List<String>)
fun test(path: List<String>, value: JsonElement)
} |
kotlin-json-patch/kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Constants.kt | 4110174786 | package com.reidsync.kxjsonpatch
open class Constants {
open val OP = "op"
open val VALUE = "value"
open val PATH = "path"
open val FROM = "from"
}
|
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/js-libs-samples-unsupported.json.kt | 2913245754 | package resources.testdata
const val TestData_JS_LIB_SAMPLES_UNSUPPORTED: String = """
{
"errors": [
{ "node": ["foo", "bar"],
"op": [{"op": "test", "path": "/1e0", "value": "bar"}],
"message": "test op shouldn't get array element 1" },
{ "node": {"foo": {"bar": [1, 2, 5, 4]}},
"op": [{"op": "test", "path": "/foo", "value": [1, 2]}],
"message": "test op should fail" }
],
"ops": [
{ "message": "test against implementation-specific numeric parsing",
"node": {"1e0": "foo"},
"op": [{"op": "test", "path": "/1e0", "value": "foo"}],
"expected": {"1e0": "foo"} },
{ "message": "spurious patch properties",
"node": {"foo": 1},
"op": [{"op": "test", "path": "/foo", "value": 1, "spurious": 1}],
"expected": {"foo": 1} },
{ "node": {"foo": null},
"op": [{"op": "test", "path": "/foo", "value": null}],
"message": "null value should be valid obj property" },
{ "node": {"foo": null},
"op": [{"op": "move", "from": "/foo", "path": "/bar"}],
"expected": {"bar": null},
"message": "null value should be valid obj property to be moved" },
{ "node": {"foo": null},
"op": [{"op": "copy", "from": "/foo", "path": "/bar"}],
"expected": {"foo": null, "bar": null},
"message": "null value should be valid obj property to be copied" },
{ "node": {"foo": {"foo": 1, "bar": 2}},
"op": [{"op": "test", "path": "/foo", "value": {"bar": 2, "foo": 1}}],
"message": "test should pass despite rearrangement" },
{ "node": {"foo": [{"foo": 1, "bar": 2}]},
"op": [{"op": "test", "path": "/foo", "value": [{"bar": 2, "foo": 1}]}],
"message": "test should pass despite (nested) rearrangement" },
{ "node": {"foo": {"bar": [1, 2, 5, 4]}},
"op": [{"op": "test", "path": "/foo", "value": {"bar": [1, 2, 5, 4]}}],
"message": "test should pass - no error" },
{ "message": "Whole document",
"node": { "foo": 1 },
"op": [{"op": "test", "path": "", "value": {"foo": 1}}],
"disabled": true },
{ "message": "Empty-string element",
"node": { "": 1 },
"op": [{"op": "test", "path": "/", "value": 1}] },
{ "node": {
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
},
"op": [{"op": "test", "path": "/foo", "value": ["bar", "baz"]},
{"op": "test", "path": "/foo/0", "value": "bar"},
{"op": "test", "path": "/", "value": 0},
{"op": "test", "path": "/a~1b", "value": 1},
{"op": "test", "path": "/c%d", "value": 2},
{"op": "test", "path": "/e^f", "value": 3},
{"op": "test", "path": "/g|h", "value": 4},
{"op": "test", "path": "/i\\j", "value": 5},
{"op": "test", "path": "/k\"l", "value": 6},
{"op": "test", "path": "/ ", "value": 7},
{"op": "test", "path": "/m~0n", "value": 8}] },
{ "node": {"baz": [{"qux": "hello"}], "bar": 1},
"op": [{"op": "copy", "from": "/baz/0", "path": "/boo"}],
"expected": {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}} },
{ "message": "replacing the root of the document is possible with add",
"node": {"foo": "bar"},
"op": [{"op": "add", "path": "", "value": {"baz": "qux"}}],
"expected": {"baz":"qux"}},
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/diff.kt | 4239071730 | package resources.testdata
const val TestData_DIFF: String = """
[
{
"message": "empty patch if no changes",
"first": "hello",
"second": "hello",
"patch": []
},
{
"message": "array members appended use special end-of-array pointer",
"first": [ 1, 2, 3 ],
"second": [ 1, 2, 3, 4, 5 ],
"patch": [
{ "op": "add", "path": "/-", "value": 4 },
{ "op": "add", "path": "/-", "value": 5 }
]
},
{
"message": "array members are correctly deleted",
"first": [ 1, 2, 3 ],
"second": [ 1 ],
"patch": [
{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/1" }
]
},
{
"message": "single object member is deleted",
"first": { "a": "b", "c": "d" },
"second": { "a": "b" },
"patch": [
{ "op": "remove", "path": "/c" }
]
},
{
"message": "added object members are in natural order",
"first": { "a": 1 },
"second": { "a": 1, "c": 2, "b": 3, "d": 4 },
"patch": [
{ "op": "add", "path": "/b", "value": 3 },
{ "op": "add", "path": "/c", "value": 2 },
{ "op": "add", "path": "/d", "value": 4 }
]
},
{
"message": "single object value change is replaced",
"first": { "a": null },
"second": { "a": 6 },
"patch": [
{ "op": "replace", "path": "/a", "value": 6 }
]
},
{
"message": "full value replacement is accounted for",
"first": [ 1, 2, 3 ],
"second": { "hello": "world" },
"patch": [
{ "op": "replace", "path": "", "value": { "hello": "world" } }
]
},
{
"message": "embedded object addition/replacement works",
"first": {
"a": "b",
"c": {
"d": "e"
}
},
"second": {
"a": "b",
"c": {
"d": 1,
"e": "f"
}
},
"patch": [
{ "op": "add", "path": "/c/e", "value": "f" },
{ "op": "replace", "path": "/c/d", "value": 1 }
]
},
{
"message": "embedded array addition/replacement works",
"first": {
"a": [ 1, 2, 3 ]
},
"second": {
"a": [ "b", 2, 3, 4 ]
},
"patch": [
{ "op": "replace", "path": "/a/0", "value": "b" },
{ "op": "add", "path": "/a/-", "value": 4 }
]
},
{
"message": "embedded object addition/replacement works (#2)",
"first": [ { "a": "b" }, "foo", { "bar": null } ],
"second": [ { "a": "b", "c": "d" }, "foo", { "bar": "baz" } ],
"patch": [
{ "op": "add", "path": "/0/c", "value": "d" },
{ "op": "replace", "path": "/2/bar", "value": "baz" }
]
},
{
"message": "embedded array addition/replacement works (#2)",
"first": [ 1, [ 2, 3 ], 4 ],
"second": [ "x", [ 2, 3, "y" ], 4 ],
"patch": [
{ "op": "replace", "path": "/0", "value": "x" },
{ "op": "add", "path": "/1/-", "value": "y" }
]
}
]
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/debug.json.kt | 1267979185 | package resources.testdata
const val TestData_DEBUG: String = """
[
{
"first":{"compare":{"":"a"},"tags":{}},
"second":{"compare":{"":"b"},"tags":{"a":"b"}}
}
]
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/rfc6902-samples-unsupported.json.kt | 1208720709 | package resources.testdata
const val TestData_RFC6902_SAMPLES_UNSUPPORTED: String = """
{
"errors": [
{
"message": "A.9. Testing a Value: Error",
"op": [{ "op": "test", "path": "/baz", "value": "bar" }],
"node": { "baz": "qux" }
},
{
"message": "A.15. Comparing Strings and Numbers",
"op": [{"op": "test", "path": "/~01", "value": "10"}],
"node": {
"/": 9,
"~1": 10
}
}
],
"ops": [
{
"message": "A.8. Testing a Value: Success",
"op": [{ "op": "test", "path": "/baz", "value": "qux" },
{ "op": "test", "path": "/foo/1", "value": 2 }],
"node": {
"baz": "qux",
"foo": [ "a", 2, "c" ]
}
},
{
"message": "A.14. ~ Escape Ordering",
"op": [{"op": "test", "path": "/~01", "value": 10}],
"node": {
"/": 9,
"~1": 10
},
"expected": {
"/": 9,
"~1": 10
}
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/replace-unsupported.json.kt | 2758303027 | package resources.testdata
const val TestData_REPLACE_UNSUPPORTED: String = """
{
"errors": [
{
"op": [{ "op": "replace", "path": "/x/y", "value": 42 }],
"node": { "x": {} },
"message": "jsonPatch.noSuchPath"
}
],
"ops": [
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/rfc6902-samples.json.kt | 4277760260 | package resources.testdata
const val TestData_RFC6902_SAMPLES: String = """
{
"errors": [
{
"message": "A.13. Invalid JSON Patch Document",
"op": [{ "op": "add", "path": "/baz", "value": "qux", "op": "remove" }],
"node": { "foo": "bar" },
"disabled": true
},
{
"message": "A.12. Adding to a Nonexistent Target",
"op": [{ "op": "add", "path": "/baz/bat", "value": "qux" }],
"node": { "foo": "bar" }
}
],
"ops": [
{
"message": "A.1. Adding an Object Member",
"op": [{ "op": "add", "path": "/baz", "value": "qux" }],
"node": { "foo": "bar" },
"expected": {
"baz": "qux",
"foo": "bar"
}
},
{
"message": "A.2. Adding an Array Element",
"op": [{ "op": "add", "path": "/foo/1", "value": "qux" }],
"node": { "foo": [ "bar", "baz" ] },
"expected": { "foo": [ "bar", "qux", "baz" ] }
},
{
"message": "A.3. Removing an Object Member",
"op": [ { "op": "remove", "path": "/baz" }],
"node": {
"baz": "qux",
"foo": "bar"
},
"expected": { "foo": "bar" }
},
{
"message": "A.4. Removing an Array Element",
"op": [{ "op": "remove", "path": "/foo/1" }],
"node": { "foo": [ "bar", "qux", "baz" ] },
"expected": { "foo": [ "bar", "baz" ] }
},
{
"message": "A.5. Replacing a Value",
"op": [{ "op": "replace", "path": "/baz", "value": "boo" }],
"node": {
"baz": "qux",
"foo": "bar"
},
"expected": {
"baz": "boo",
"foo": "bar"
}
},
{
"message": "A.6. Moving a Value",
"op": [{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }],
"node": {
"foo": {
"bar": "baz",
"waldo": "fred"
},
"qux": {
"corge": "grault"
}
},
"expected": {
"foo": {
"bar": "baz"
},
"qux": {
"corge": "grault",
"thud": "fred"
}
}
},
{
"message": "A.7. Moving an Array Element",
"op": [{ "op": "move", "from": "/foo/1", "path": "/foo/3" }],
"node": { "foo": [ "all", "grass", "cows", "eat" ] },
"expected": { "foo": [ "all", "cows", "eat", "grass" ] }
},
{
"message": "A.10. Adding a Nested Member Object",
"op": [{ "op": "add", "path": "/child", "value": { "grandchild": { } } }],
"node": { "foo": "bar" },
"expected": {
"foo": "bar",
"child": {
"grandchild": {
}
}
}
},
{
"message": "A.11. Ignoring Unrecognized Elements",
"op": [{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }],
"node": { "foo": "bar" },
"expected": {
"foo": "bar",
"baz": "qux"
}
},
{
"message": "A.16. Adding an Array Value",
"op": [{ "op": "add", "path": "/foo/-", "value": ["abc", "def"] }],
"node": { "foo": ["bar"] },
"expected": { "foo": ["bar", ["abc", "def"]] }
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/move.json.kt | 3313062794 | package resources.testdata
const val TestData_MOVE: String = """
{
"errors": [
{
"op": [{ "op": "move", "from": "/a", "path": "/a/b" }],
"node": {},
"message": "jsonPatch.noSuchPath"
},
{
"op": [{ "op": "move", "from": "/a", "path": "/b/c" }],
"node": { "a": "b" },
"message": "jsonPatch.noSuchParent"
},
{
"op": [{ "op": "move", "path": "/b/c" }],
"node": { "a": "b" },
"message": "Missing from field"
}
],
"ops": [
{
"op": [{ "op": "move", "from": "/x/a", "path": "/x/b" }],
"node": { "x": { "a": "helo" } },
"expected": { "x": { "b": "helo" } }
},
{
"op": [{ "op": "move", "from": "/x/a", "path": "/x/a" }],
"node": { "x": { "a": "helo" } },
"expected": { "x": { "a": "helo" } }
},
{
"op": [{ "op": "move", "from": "/0", "path": "/0/x" }],
"node": [ "victim", {}, {} ],
"expected": [ { "x": "victim" }, {} ]
},
{
"op": [{ "op": "move", "from": "/0", "path": "/-" }],
"node": [ 0, 1, 2 ],
"expected": [ 1, 2, 0 ]
},
{
"op": [{ "op": "move", "from": "/a", "path": "/b/2" }],
"node": { "a": "helo", "b": [ 1, 2, 3, 4 ] },
"expected": { "b": [ 1, 2, "helo", 3, 4 ] }
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/js-libs-samples.json.kt | 1848453415 | package resources.testdata
const val TestData_JS_LIB_SAMPLES: String = """
{
"errors": [
{ "node": {"bar": [1, 2]},
"op": [{"op": "add", "path": "/bar/8", "value": "5"}],
"message": "Out of bounds (upper)" },
{ "node": {"bar": [1, 2]},
"op": [{"op": "add", "path": "/bar/-1", "value": "5"}],
"message": "Out of bounds (lower)" },
{ "node": ["foo", "sil"],
"op": [{"op": "add", "path": "/bar", "value": 42}],
"message": "Object operation on array target" },
{ "node": {"foo": 1, "baz": [{"qux": "hello"}]},
"op": [{"op": "remove", "path": "/baz/1e0/qux"}],
"message": "remove op shouldn't remove from array with bad number" },
{ "node": [1, 2, 3, 4],
"op": [{"op": "remove", "path": "/1e0"}],
"message": "remove op shouldn't remove from array with bad number" },
{ "node": [""],
"op": [{"op": "replace", "path": "/1e0", "value": false}],
"message": "replace op shouldn't replace in array with bad number" },
{ "node": {"baz": [1,2,3], "bar": 1},
"op": [{"op": "copy", "from": "/baz/1e0", "path": "/boo"}],
"message": "copy op shouldn't work with bad number" },
{ "node": {"foo": 1, "baz": [1,2,3,4]},
"op": [{"op": "move", "from": "/baz/1e0", "path": "/foo"}],
"message": "move op shouldn't work with bad number" },
{ "node": ["foo", "sil"],
"op": [{"op": "add", "path": "/1e0", "value": "bar"}],
"message": "add op shouldn't add to array with bad number" },
{ "node": [ 1 ],
"op": [ { "op": "add", "path": "/-" } ],
"message": "missing 'value' parameter" },
{ "node": [ 1 ],
"op": [ { "op": "replace", "path": "/0" } ],
"message": "missing 'value' parameter" },
{ "node": [ null ],
"op": [ { "op": "test", "path": "/0" } ],
"message": "missing 'value' parameter" },
{ "node": [ false ],
"op": [ { "op": "test", "path": "/0" } ],
"message": "missing 'value' parameter" },
{ "node": [ 1 ],
"op": [ { "op": "copy", "path": "/-" } ],
"message": "missing 'from' parameter" },
{ "node": { "foo": 1 },
"op": [ { "op": "move", "path": "" } ],
"message": "missing 'from' parameter" },
{ "node": { "foo": "bar" },
"op": [ { "op": "add", "path": "/baz", "value": "qux",
"op": "move", "from":"/foo" } ],
"message": "patch has two 'op' members",
"disabled": true },
{ "node": {"foo": 1},
"op": [{"op": "spam", "path": "/foo", "value": 1}],
"message": "Unrecognized op 'spam'" }
],
"ops": [
{ "message": "replacing the root of the document is possible with add",
"node": {"foo": "bar"},
"op": [{"op": "add", "path": "", "value": {"baz": "qux"}}],
"expected": {"baz":"qux"}},
{ "message": "replacing the root of the document is possible with add",
"node": {"foo": "bar"},
"op": [{"op": "add", "path": "", "value": ["baz", "qux"]}],
"expected": ["baz", "qux"]},
{ "message": "empty list, empty docs",
"node": {},
"op": [],
"expected": {} },
{ "message": "empty patch list",
"node": {"foo": 1},
"op": [],
"expected": {"foo": 1} },
{ "message": "rearrangements OK?",
"node": {"foo": 1, "bar": 2},
"op": [],
"expected": {"bar":2, "foo": 1} },
{ "message": "rearrangements OK? How about one level down ... array",
"node": [{"foo": 1, "bar": 2}],
"op": [],
"expected": [{"bar":2, "foo": 1}] },
{ "message": "rearrangements OK? How about one level down...",
"node": {"foo":{"foo": 1, "bar": 2}},
"op": [],
"expected": {"foo":{"bar":2, "foo": 1}} },
{ "message": "add replaces any existing field",
"node": {"foo": null},
"op": [{"op": "add", "path": "/foo", "value":1}],
"expected": {"foo": 1} },
{ "message": "toplevel array",
"node": [],
"op": [{"op": "add", "path": "/0", "value": "foo"}],
"expected": ["foo"] },
{ "message": "toplevel array, no change",
"node": ["foo"],
"op": [],
"expected": ["foo"] },
{ "message": "toplevel object, numeric string",
"node": {},
"op": [{"op": "add", "path": "/foo", "value": "1"}],
"expected": {"foo":"1"} },
{ "message": "toplevel object, integer",
"node": {},
"op": [{"op": "add", "path": "/foo", "value": 1}],
"expected": {"foo":1} },
{ "message": "Toplevel scalar values OK?",
"node": "foo",
"op": [{"op": "replace", "path": "", "value": "bar"}],
"expected": "bar",
"disabled": true },
{ "message": "Add, / target",
"node": {},
"op": [ {"op": "add", "path": "/", "value":1 } ],
"expected": {"":1} },
{ "message": "Add composite value at top level",
"node": {"foo": 1},
"op": [{"op": "add", "path": "/bar", "value": [1, 2]}],
"expected": {"foo": 1, "bar": [1, 2]} },
{ "message": "Add into composite value",
"node": {"foo": 1, "baz": [{"qux": "hello"}]},
"op": [{"op": "add", "path": "/baz/0/foo", "value": "world"}],
"expected": {"foo": 1, "baz": [{"qux": "hello", "foo": "world"}]} },
{ "node": {"foo": 1},
"op": [{"op": "add", "path": "/bar", "value": true}],
"expected": {"foo": 1, "bar": true} },
{ "node": {"foo": 1},
"op": [{"op": "add", "path": "/bar", "value": false}],
"expected": {"foo": 1, "bar": false} },
{ "node": {"foo": 1},
"op": [{"op": "add", "path": "/bar", "value": null}],
"expected": {"foo": 1, "bar": null} },
{ "message": "0 can be an array index or object element name",
"node": {"foo": 1},
"op": [{"op": "add", "path": "/0", "value": "bar"}],
"expected": {"foo": 1, "0": "bar" } },
{ "node": ["foo"],
"op": [{"op": "add", "path": "/1", "value": "bar"}],
"expected": ["foo", "bar"] },
{ "node": ["foo", "sil"],
"op": [{"op": "add", "path": "/1", "value": "bar"}],
"expected": ["foo", "bar", "sil"] },
{ "node": ["foo", "sil"],
"op": [{"op": "add", "path": "/0", "value": "bar"}],
"expected": ["bar", "foo", "sil"] },
{ "node": ["foo", "sil"],
"op": [{"op":"add", "path": "/2", "value": "bar"}],
"expected": ["foo", "sil", "bar"] },
{ "node": ["foo", "sil"],
"op": [{"op": "add", "path": "/1", "value": ["bar", "baz"]}],
"expected": ["foo", ["bar", "baz"], "sil"],
"message": "value in array add not flattened" },
{ "node": {"foo": 1, "bar": [1, 2, 3, 4]},
"op": [{"op": "remove", "path": "/bar"}],
"expected": {"foo": 1} },
{ "node": {"foo": 1, "baz": [{"qux": "hello"}]},
"op": [{"op": "remove", "path": "/baz/0/qux"}],
"expected": {"foo": 1, "baz": [{}]} },
{ "node": {"foo": 1, "baz": [{"qux": "hello"}]},
"op": [{"op": "replace", "path": "/foo", "value": [1, 2, 3, 4]}],
"expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]} },
{ "node": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]},
"op": [{"op": "replace", "path": "/baz/0/qux", "value": "world"}],
"expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "world"}]} },
{ "node": ["foo"],
"op": [{"op": "replace", "path": "/0", "value": "bar"}],
"expected": ["bar"] },
{ "node": [""],
"op": [{"op": "replace", "path": "/0", "value": 0}],
"expected": [0] },
{ "node": [""],
"op": [{"op": "replace", "path": "/0", "value": true}],
"expected": [true] },
{ "node": [""],
"op": [{"op": "replace", "path": "/0", "value": false}],
"expected": [false] },
{ "node": [""],
"op": [{"op": "replace", "path": "/0", "value": null}],
"expected": [null] },
{ "node": ["foo", "sil"],
"op": [{"op": "replace", "path": "/1", "value": ["bar", "baz"]}],
"expected": ["foo", ["bar", "baz"]],
"message": "value in array replace not flattened" },
{ "message": "replace whole document",
"node": {"foo": "bar"},
"op": [{"op": "replace", "path": "", "value": {"baz": "qux"}}],
"expected": {"baz": "qux"} },
{ "node": {"foo": null},
"op": [{"op": "replace", "path": "/foo", "value": "truthy"}],
"expected": {"foo": "truthy"},
"message": "null value should be valid obj property to be replaced with something truthy" },
{ "node": {"foo": null},
"op": [{"op": "remove", "path": "/foo"}],
"expected": {},
"message": "null value should be valid obj property to be removed" },
{ "node": {"foo": "bar"},
"op": [{"op": "replace", "path": "/foo", "value": null}],
"expected": {"foo": null},
"message": "null value should still be valid obj property replace other value" },
{ "message": "Move to same location has no effect",
"node": {"foo": 1},
"op": [{"op": "move", "from": "/foo", "path": "/foo"}],
"expected": {"foo": 1} },
{ "node": {"foo": 1, "baz": [{"qux": "hello"}]},
"op": [{"op": "move", "from": "/foo", "path": "/bar"}],
"expected": {"baz": [{"qux": "hello"}], "bar": 1} },
{ "node": {"baz": [{"qux": "hello"}], "bar": 1},
"op": [{"op": "move", "from": "/baz/0/qux", "path": "/baz/1"}],
"expected": {"baz": [{}, "hello"], "bar": 1} },
{ "message": "Adding to \"/-\" adds to the end of the array",
"node": [ 1, 2 ],
"op": [ { "op": "add", "path": "/-", "value": { "foo": [ "bar", "baz" ] } } ],
"expected": [ 1, 2, { "foo": [ "bar", "baz" ] } ]},
{ "message": "Adding to \"/-\" adds to the end of the array, even n levels down",
"node": [ 1, 2, [ 3, [ 4, 5 ] ] ],
"op": [ { "op": "add", "path": "/2/1/-", "value": { "foo": [ "bar", "baz" ] } } ],
"expected": [ 1, 2, [ 3, [ 4, 5, { "foo": [ "bar", "baz" ] } ] ] ]},
{ "message": "test remove on array",
"node": [1, 2, 3, 4],
"op": [{"op": "remove", "path": "/0"}],
"expected": [2, 3, 4] },
{ "message": "test repeated removes",
"node": [1, 2, 3, 4],
"op": [{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/2" }],
"expected": [1, 3] }
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/remove-unsupported.json.kt | 2269369405 | package resources.testdata
const val TestData_REMOVE_UNSUPPORTED: String = """
{
"errors": [
{
"op": [{ "op": "remove", "path": "/x/y" }],
"node": { "x": {} },
"message": "jsonPatch.noSuchPath"
}
],
"ops": [
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/replace.json.kt | 4086506393 | package resources.testdata
const val TestData_REPLACE: String = """
{
"errors": [
{
"op": [{ "op": "replace", "path": "/a" }],
"node": { "a": 0 },
"message": "Missing value field"
},
{
"op": [{ "op": "replace", "path": "/x/y", "value": false }],
"node": { "x": "a" }
}
],
"ops": [
{
"op": [{ "op": "replace", "path": "", "value": false }],
"node": { "x": { "a": "b", "y": {} } },
"expected": false
},
{
"op": [{ "op": "replace", "path": "/x/y", "value": "hello" }],
"node": { "x": { "a": "b", "y": {} } },
"expected": { "x": { "a": "b", "y": "hello" } }
},
{
"op": [{ "op": "replace", "path": "/0/2", "value": "x" }],
"node": [ [ "a", "b", "c"], "d", "e" ],
"expected": [ [ "a", "b", "x" ], "d", "e" ]
},
{
"op": [{ "op": "replace", "path": "/x/0", "value": null }],
"node": { "x": [ "y", "z" ], "foo": "bar" },
"expected": { "x": [ null, "z" ], "foo": "bar" }
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/diff-unsupported.json.kt | 2108414453 | package resources.testdata
const val TestData_DIFF_UNSUPPORTED: String = """
[
{
"message": "similar element is copied instead of added",
"first": {
"a": "c"
},
"second": {
"a": "c",
"d": "c"
},
"patch": [
{ "op": "copy", "path": "/d", "from": "/a" }
]
},
{
"message": "similar element removed then added is moved instead",
"first": { "a": "b" },
"second": { "c": "b" },
"patch": [
{ "op": "move", "path": "/c", "from": "/a" }
]
}
]
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/remove.json.kt | 4046215904 | package resources.testdata
const val TestData_REMOVE: String = """
{
"errors": [
{
"op": [{ "op": "remove", "path": "/x/y" }],
"node": { "x": "just a string" }
},
{
"op": [{ "op": "remove", "path": "/x/1" }],
"node": { "x": [ "single" ] }
}
],
"ops": [
{
"op": [{ "op": "remove", "path": "/x/y" }],
"node": { "x": { "a": "b", "y": {} } },
"expected": { "x": { "a": "b" } }
},
{
"op": [{ "op": "remove", "path": "/0/2" }],
"node": [ [ "a", "b", "c"], "d", "e" ],
"expected": [ [ "a", "b" ], "d", "e" ]
},
{
"op": [{ "op": "remove", "path": "/x/0" }],
"node": { "x": [ "y", "z" ], "foo": "bar" },
"expected": { "x": [ "z" ], "foo": "bar" }
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/add.json.kt | 1396717363 | package resources.testdata
const val TestData_ADD: String = """
{
"errors": [
{
"op": [{ "op": "add", "path": "/a" }],
"node": {},
"message": "Missing value field on add operation"
}
],
"ops": [
{
"op": [{ "op": "add", "path": "/a", "value": "b" }],
"node": {},
"expected": { "a": "b" }
},
{
"op": [{ "op": "add", "path": "/a", "value": 1 }],
"node": { "a": "b" },
"expected": { "a": 1 }
},
{
"op": [{ "op": "add", "path": "/array/-", "value": 1 }],
"node": { "array": [ 2, null, {}, 1 ] },
"expected": { "array": [ 2, null, {}, 1, 1 ] }
},
{
"op": [{ "op": "add", "path": "/array/2", "value": "hello" }],
"node": { "array": [ 2, null, {}, 1] },
"expected": { "array": [ 2, null, "hello", {}, 1 ] }
},
{
"op": [{ "op": "add", "path": "/obj/inner/b", "value": [ 1, 2 ] }],
"node": {
"obj": {
"inner": {
"a": "hello"
}
}
},
"expected": {
"obj": {
"inner": {
"a": "hello",
"b": [ 1, 2 ]
}
}
}
},
{
"op": [{ "op": "add", "path": "/obj/inner/b", "value": [ 1, 2 ] }],
"node": {
"obj": {
"inner": {
"a": "hello",
"b": "world"
}
}
},
"expected": {
"obj": {
"inner": {
"a": "hello",
"b": [ 1, 2 ]
}
}
}
},
{
"message": "support of path with /",
"op": [{ "op": "add", "path": "/b~1c~1d/3", "value": 4 }],
"node": { "b/c/d": [1, 2, 3] },
"expected": { "b/c/d": [1, 2, 3, 4] }
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/add-unsupported.json.kt | 121510567 | package resources.testdata
const val TestData_ADD_UNSUPPORTED: String = """
{
"errors": [
{
"op": [{ "op": "add", "path": "/a/b/c", "value": 1 }],
"node": { "a": "b" },
"message": "jsonPatch.noSuchParent"
},
{
"op": [{ "op": "add", "path": "/~1", "value": 1 }],
"node": [],
"message": "jsonPatch.notAnIndex"
},
{
"op": [{ "op": "add", "path": "/3", "value": 1 }],
"node": [ 1, 2 ],
"message": "jsonPatch.noSuchIndex"
},
{
"op": [{ "op": "add", "path": "/-2", "value": 1 }],
"node": [ 1, 2 ],
"message": "jsonPatch.noSuchIndex"
},
{
"op": [{ "op": "add", "path": "/foo/f", "value": "bar" }],
"node": { "foo": "bar" },
"message": "jsonPatch.parentNotContainer"
}
],
"ops": [
{
"op": [{ "op": "add", "path": "", "value": null }],
"node": {},
"expected": null
}
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/move-unsupported.json.kt | 154074134 | package resources.testdata
const val TestData_MOVE_UNSUPPORTED: String = """
{
"errors": [
{
"op": [{ "op": "move", "from": "/a", "path": "/a/b" }],
"node": {},
"message": "jsonPatch.noSuchPath"
},
{
"op": [{ "op": "move", "from": "/a", "path": "/b/c" }],
"node": { "a": "b" },
"message": "jsonPatch.noSuchParent"
}
],
"ops": [
]
}
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/resources/sample.json.kt | 1358048208 | package resources.testdata
const val TestData_SAMPLE: String = """
[
{
"first": { "a": 1 },
"second": { "b": 2 }
},
{
"first": { "a": null },
"second": { "b": 1 }
},
{
"first": {},
"second": {}
},
{
"first": { "a": 0.1 },
"second": { "b": 0.1 }
},
{
"first": {},
"second": {
"a": "b"
}
},
{
"first": {
"a": "b"
},
"second": {}
},
{
"first": {
"a": "b"
},
"second": {
"a": "c"
}
},
{
"first": [],
"second": [
"a"
]
},
{
"first": [
"hello",
"world"
],
"second": [
"hello",
"world!"
]
},
{
"first": {
"a": "b",
"c": [
"d"
]
},
"second": {
"a": "b",
"c": [
"d",
"e"
]
}
},
{
"first": [
1,
2,
3,
4
],
"second": [
0,
2,
3
]
},
{
"first": [
"a",
{
"b": "c"
},
{
"d": [
1,
2
]
}
],
"second": [
"x",
{
"b": 1
},
{
"d": [
1,
3,
""
]
},
null
]
},
{
"first": {
"b": "a"
},
"second": {
"c": "a"
}
},
{
"first": {
"b": [
1,
2
]
},
"second": {
"c": [
1,
2
]
}
},
{
"first": [
0,
1,
2
],
"second": [
1,
2,
0
]
},
{
"first": [
0,
1,
2,
3,
4,
5
],
"second": [
1,
3,
4,
0,
5
]
},
{
"first": [
0,
1,
2,
3,
4,
5,
6,
7
],
"second": [
3,
6,
4,
5,
7
]
},
{
"first": {
"b": [
0,
1,
2,
3
],
"c": [
1
]
},
"second": {
"b": [
1,
3
],
"c": [
0,
1
]
}
},
{
"first": {
"b": [
0,
1,
2,
3
],
"c": [
1
],
"d": []
},
"second": {
"b": [
1,
3
],
"c": [
2,
1
],
"d": [
0
]
}
},
{
"first": {
"a": 0,
"b": [
1,
2
]
},
"second": {
"b": [
1,
2,
0
]
}
},
{
"first": {
"b": [
0,
1,
2
]
},
"second": {
"b": [
1,
2
],
"c": 0
}
},
{
"first": {
"b": [
0,
1,
3,
4,
5
]
},
"second": {
"b": [
1,
2,
3,
5
],
"c": 0
}
},
{
"first": {
"b": [
0,
1,
3,
4,
5
]
},
"second": {
"b": [
1,
2,
3,
5
],
"c": 0,
"d": 4
}
},
{
"first": {
"b": [
0,
1,
2,
3,
4,
5,
6,
7,
8
]
},
"second": {
"b": [
1,
6,
2,
3,
5,
7,
0,
8
],
"c": 4
}
},
{
"first": {
"b": [
0,
1,
2,
3,
4,
5,
6,
7,
8
]
},
"second": {
"b": [
1,
3,
6,
4,
5,
7,
8
],
"c": 2
}
},
{
"first": {
"b": [
0,
1,
2,
3,
4,
5,
6,
7,
8
]
},
"second": {
"b": [
1,
3,
6,
4,
5,
7,
0,
8
],
"c": 2
}
},
{
"first": {},
"second": {
"a": 1,
"b": 1
},
"patch": [
{
"op": "ADD",
"path": "[b]",
"value": 1
},
{
"op": "ADD",
"path": "[a]",
"value": 1
}
]
},
{
"first": {},
"second": {
"a": {
"a": 1
},
"b": {
"a": 1
}
}
},
{
"first": [],
"second": [
[
0
],
[
0
]
]
},
{
"first": [
"eol"
],
"second": [
{
"a": 1
},
{
"a": 1
},
[],
[],
[
0
],
[
0
],
"eol"
]
},
{
"first": [
1,
2
],
"second": [
2,
1
]
},
{
"first": [
{
"name": "a"
},
{
"name": "b"
},
{
"name": "c"
}
],
"second": [
{
"name": "b"
}
]
},
{
"first": [
1,
2,
3,
4,
5,
{
"0": "0"
}
],
"second": [
1,
2,
4,
5,
{
"a": "0"
}
]
},
{
"first": [
"a",
"b",
"c",
"d",
"e"
],
"second": [
"e",
"a",
"f",
"c",
"d",
"b"
]
},
{
"first": [
0,
1,
2,
3,
4,
5
],
"second": [
1,
3,
4,
0,
5
]
},
{
"first": {},
"second": {}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1
}
},
{
"first": {
"foo": 1,
"bar": 2
},
"second": {
"bar": 2,
"foo": 1
}
},
{
"first": [
{
"foo": 1,
"bar": 2
}
],
"second": [
{
"bar": 2,
"foo": 1
}
]
},
{
"first": {
"foo": {
"foo": 1,
"bar": 2
}
},
"second": {
"foo": {
"bar": 2,
"foo": 1
}
}
},
{
"first": {
"foo": null
},
"second": {
"foo": 1
}
},
{
"first": [],
"second": [
"foo"
]
},
{
"first": [
"foo"
],
"second": [
"foo"
]
},
{
"first": {},
"second": {
"foo": "1"
}
},
{
"first": {},
"second": {
"foo": 1
}
},
{
"first": {},
"second": {
"": 1
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1,
"bar": [
1,
2
]
}
},
{
"first": {
"foo": 1,
"baz": [
{
"qux": "hello"
}
]
},
"second": {
"foo": 1,
"baz": [
{
"qux": "hello",
"foo": "world"
}
]
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1,
"bar": true
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1,
"bar": false
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1,
"bar": null
}
},
{
"first": {
"foo": 1
},
"second": {
"0": "bar",
"foo": 1
}
},
{
"first": [
"foo"
],
"second": [
"foo",
"bar"
]
},
{
"first": [
"foo",
"sil"
],
"second": [
"foo",
"bar",
"sil"
]
},
{
"first": [
"foo",
"sil"
],
"second": [
"bar",
"foo",
"sil"
]
},
{
"first": [
"foo",
"sil"
],
"second": [
"foo",
"sil",
"bar"
]
},
{
"first": {
"1e0": "foo"
},
"second": {
"1e0": "foo"
}
},
{
"first": [
"foo",
"sil"
],
"second": [
"foo",
[
"bar",
"baz"
],
"sil"
]
},
{
"first": {
"foo": 1,
"bar": [
1,
2,
3,
4
]
},
"second": {
"foo": 1
}
},
{
"first": {
"foo": 1,
"baz": [
{
"qux": "hello"
}
]
},
"second": {
"foo": 1,
"baz": [
{}
]
}
},
{
"first": {
"foo": 1,
"baz": [
{
"qux": "hello"
}
]
},
"second": {
"foo": [
1,
2,
3,
4
],
"baz": [
{
"qux": "hello"
}
]
}
},
{
"first": {
"foo": [
1,
2,
3,
4
],
"baz": [
{
"qux": "hello"
}
]
},
"second": {
"foo": [
1,
2,
3,
4
],
"baz": [
{
"qux": "world"
}
]
}
},
{
"first": [
"foo"
],
"second": [
"bar"
]
},
{
"first": [
""
],
"second": [
0
]
},
{
"first": [
""
],
"second": [
true
]
},
{
"first": [
""
],
"second": [
false
]
},
{
"first": [
""
],
"second": [
null
]
},
{
"first": [
"foo",
"sil"
],
"second": [
"foo",
[
"bar",
"baz"
]
]
},
{
"first": {
"foo": "bar"
},
"second": {
"baz": "qux"
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1
}
},
{
"first": {
"foo": 1
},
"second": {
"foo": 1
}
},
{
"first": {
"foo": 1,
"baz": [
{
"qux": "hello"
}
]
},
"second": {
"baz": [
{
"qux": "hello"
}
],
"bar": 1
}
},
{
"first": {
"baz": [
{
"qux": "hello"
}
],
"bar": 1
},
"second": {
"baz": [
{},
"hello"
],
"bar": 1
}
},
{
"first": {
"baz": [
{
"qux": "hello"
}
],
"bar": 1
},
"second": {
"baz": [
{
"qux": "hello"
}
],
"bar": 1,
"boo": {
"qux": "hello"
}
}
},
{
"first": {
"foo": "bar"
},
"second": {
"baz": "qux"
}
},
{
"first": [
1,
2
],
"second": [
1,
2,
{
"foo": [
"bar",
"baz"
]
}
]
},
{
"first": [
1,
2,
[
3,
[
4,
5
]
]
],
"second": [
1,
2,
[
3,
[
4,
5,
{
"foo": [
"bar",
"baz"
]
}
]
]
]
},
{
"first": [
1,
2,
3,
4
],
"second": [
2,
3,
4
]
},
{
"first": [
1,
2,
3,
4
],
"second": [
1,
3
]
},
{
"first":{"a":{"b/c/d":"i m here"}},
"second" :{"a":{"b/c/d":"i m not here"}}
},
{
"first": {"b":[0,1,2,3]},
"second": {"b":[1,3],"c":0}
},
{
"first": {
"c_i": [
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 419,
"nm": "Children"
},
{
"id": 420,
"nm": "General"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5796,
"nm": "Fantasy"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5800,
"nm": "Horror And Ghost Stories"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 419,
"nm": "Children"
},
{
"id": 420,
"nm": "General"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5796,
"nm": "Fantasy"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5800,
"nm": "Horror And Ghost Stories"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 419,
"nm": "Children"
},
{
"id": 7991,
"nm": "Children Literature"
},
{
"id": 7993,
"nm": "Family"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5796,
"nm": "Fantasy"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5800,
"nm": "Horror And Ghost Stories"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 419,
"nm": "Children"
},
{
"id": 7991,
"nm": "Children Literature"
},
{
"id": 7993,
"nm": "Family"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5796,
"nm": "Fantasy"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 4390,
"nm": "Teens"
},
{
"id": 5800,
"nm": "Horror And Ghost Stories"
}
]
},
{
"c_n_i": [
{
"id": 1,
"nm": "Books_Tree"
},
{
"id": 419,
"nm": "Children"
},
{
"id": 7991,
"nm": "Children Literature"
},
{
"id": 7993,
"nm": "Family"
}
]
}
]
},
"second": {
"c_i": [
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Fantasy",
"id": 5796
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Horror And Ghost Stories",
"id": 5800
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Children",
"id": 419
},
{
"nm": "Children Literature",
"id": 7991
},
{
"nm": "Family",
"id": 7993
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Fantasy",
"id": 5796
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Horror And Ghost Stories",
"id": 5800
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Children",
"id": 419
},
{
"nm": "Children Literature",
"id": 7991
},
{
"nm": "Family",
"id": 7993
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Children",
"id": 419
},
{
"nm": "General",
"id": 420
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Fantasy",
"id": 5796
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Horror And Ghost Stories",
"id": 5800
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Children",
"id": 419
},
{
"nm": "General",
"id": 420
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Fantasy",
"id": 5796
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Teens",
"id": 4390
},
{
"nm": "Horror And Ghost Stories",
"id": 5800
}
]
},
{
"c_n_i": [
{
"nm": "Books_Tree",
"id": 1
},
{
"nm": "Children",
"id": 419
},
{
"nm": "Children Literature",
"id": 7991
},
{
"nm": "Family",
"id": 7993
}
]
}
]
}
},
{
"first": {"b":[{"b":[2,3,4,5]},{"c":1},{"d":1},{"e":1},{"f":1}]},
"second": {"b":[{"b":1},{"c":1},{"d":1},{"e":1},{"f":[1,2,3,4,5]}]}
},
{
"first": {"a":[{"b":[{"c":[{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]}]}]},
"second": {"a":[{"b":[{"c":[{"k1":"v1"},{"k3":"v3"},{"k5":"v5"},{"k2":"v2"}]}]}]}
},
{
"first":[{"name":"winters","country":["aus","nz","sl","rsa","wi","eng"]},{"name":"winters","country":["india","aus","nz","sl"]},{"name":"autumn","country":["aus","nz","sl","rsa","wi"]},{"name":"winters","country":["aus","nz","sl","rsa","wi","eng"]},{"name":"summers","country":["nz","sl","rsa","wi","eng"]},{"name":"autumn","country":["aus","nz","sl","rsa","wi","eng"]},{"name":"rainy","country":["nz","sl"]}],
"second":[{"name":"winters","country":["india","aus","nz","sl","rsa"]},{"name":"summers","country":["nz","sl","rsa","wi","eng"]},{"name":"autumn","country":["nz","sl","rsa","wi"]},{"name":"summers","country":["india","aus","nz","sl","rsa","wi","eng"]},{"name":"autumn","country":["aus","nz","sl","rsa","wi","eng"]},{"name":"winters","country":["india","aus","nz","sl","rsa","wi","eng"]},{"name":"spring","country":["india","aus","nz","sl"]},{"name":"summers","country":["sl"]},{"name":"autumn","country":["sl","rsa","wi","eng"]}]
},
{
"first":[],
"second":[]
},
{
"first":[{"age":8,"country":["sl","rsa","wi","eng"]},{"age":9,"country":["aus","nz","sl"]},{"age":9,"country":["india","aus","nz","sl"]},{"age":8,"country":["sl"]},{"age":2,"country":["nz","sl","rsa","wi"]},{"age":7,"country":["nz","sl","rsa"]}],
"second":[{"age":10,"country":["sl"]},{"age":6,"country":["india","aus","nz","sl","rsa"]},{"age":1,"country":["sl","rsa","wi","eng"]},{"age":8,"country":["sl","rsa","wi"]},{"age":9,"country":["sl","rsa","wi"]},{"age":9,"country":["india","aus","nz","sl"]},{"age":5,"country":["aus","nz","sl","rsa","wi","eng"]},{"age":4,"country":["sl","rsa","wi","eng"]},{"age":9,"country":["india","aus","nz","sl"]}]
},
{
"first":[{"friends":"male","age":2,"name":"summers","gender":"male","country":["nz","sl","rsa","wi","eng"]},{"friends":"male","age":5,"name":"spring","gender":"male","country":["india","aus","nz","sl","rsa","wi","eng"]},{"friends":"male","age":9,"name":"spring","gender":"male","country":["india","aus","nz","sl","rsa"]},{"friends":"male","age":10,"name":"summers","gender":"female","country":["nz","sl","rsa","wi","eng"]}],
"second":[{"friends":"male","age":8,"name":"spring","gender":"female","country":["aus","nz","sl"]},{"friends":"female","age":6,"name":"summers","gender":"male","country":["india","aus","nz","sl","rsa"]},{"friends":"male","age":10,"name":"summers","gender":"female","country":["nz","sl","rsa","wi","eng"]},{"friends":"female","age":5,"name":"spring","gender":"female","country":["nz","sl"]},{"friends":"female","age":1,"name":"summers","gender":"male","country":["aus","nz","sl"]},{"friends":"male","age":2,"name":"summers","gender":"male","country":["nz","sl","rsa","wi","eng"]},{"friends":"female","age":3,"name":"spring","gender":"female","country":["india","aus","nz","sl","rsa"]},{"friends":"female","age":1,"name":"summers","gender":"female","country":["nz","sl","rsa","wi"]},{"friends":"male","age":6,"name":"rainy","gender":"male","country":["aus","nz","sl","rsa","wi","eng"]}]
},
{
"first":{"compare":{"":"a"},"tags":{}},
"second":{"compare":{"":"b"},"tags":{"a":"b"}}
}
]
""" |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/CompatibilityTest.kt | 3711440669 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class CompatibilityTest {
var mapper: GsonObjectMapper = GsonObjectMapper()
var addNodeWithMissingValue: JsonElement = mapper.readTree("[{\"op\":\"add\",\"path\":\"a\"}]")
var replaceNodeWithMissingValue: JsonElement = mapper.readTree("[{\"op\":\"replace\",\"path\":\"a\"}]")
@BeforeTest
fun setUp() {
mapper = GsonObjectMapper()
addNodeWithMissingValue = mapper.readTree("[{\"op\":\"add\",\"path\":\"a\"}]")
replaceNodeWithMissingValue = mapper.readTree("[{\"op\":\"replace\",\"path\":\"a\"}]")
}
@Test
fun withFlagAddShouldTreatMissingValuesAsNulls() {
val expected: JsonElement = mapper.readTree("{\"a\":null}")
val result: JsonElement = JsonPatch.apply(
addNodeWithMissingValue,
JsonObject(emptyMap()),
setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS)
)
assertEquals(result, expected)
}
@Test
fun withFlagAddNodeWithMissingValueShouldValidateCorrectly() {
JsonPatch.validate(
addNodeWithMissingValue,
setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS)
)
}
@Test
fun withFlagReplaceShouldTreatMissingValuesAsNull() {
val source: JsonElement = mapper.readTree("{\"a\":\"test\"}")
val expected: JsonElement = mapper.readTree("{\"a\":null}")
val result: JsonElement = JsonPatch.apply(
replaceNodeWithMissingValue,
source,
setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS)
)
assertEquals(
result,
expected
)
}
@Test
fun withFlagReplaceNodeWithMissingValueShouldValidateCorrectly() {
JsonPatch.validate(
addNodeWithMissingValue,
setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS)
)
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/MoveOperationTest.kt | 2819182862 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.JsonElement
import resources.testdata.TestData_MOVE
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* @author ctranxuan (streamdata.io).
*/
class MoveOperationTest : AbstractTest() {
private val MAPPER = GsonObjectMapper()
//@org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_MOVE)
}
@Test
fun testMoveValueGeneratedHasNoValue() {
val jsonNode1: JsonElement =
MAPPER.readTree("{ \"foo\": { \"bar\": \"baz\", \"waldo\": \"fred\" }, \"qux\": { \"corge\": \"grault\" } }")
val jsonNode2: JsonElement =
MAPPER.readTree("{ \"foo\": { \"bar\": \"baz\" }, \"qux\": { \"corge\": \"grault\", \"thud\": \"fred\" } }")
val patch: JsonElement =
MAPPER.readTree("[{\"op\":\"move\",\"from\":\"/foo/waldo\",\"path\":\"/qux/thud\"}]")
val diff: JsonElement = JsonDiff.asJson(jsonNode1, jsonNode2)
assertEquals(diff, patch)
}
@Test
fun testMoveArrayGeneratedHasNoValue() {
val jsonNode1: JsonElement =
MAPPER.readTree("{ \"foo\": [ \"all\", \"grass\", \"cows\", \"eat\" ] }")
val jsonNode2: JsonElement =
MAPPER.readTree("{ \"foo\": [ \"all\", \"cows\", \"eat\", \"grass\" ] }")
val patch: JsonElement =
MAPPER.readTree("[{\"op\":\"move\",\"from\":\"/foo/1\",\"path\":\"/foo/3\"}]")
val diff: JsonElement = JsonDiff.asJson(jsonNode1, jsonNode2)
assertEquals(diff, patch)
// assertEquals(
// diff,
// org.hamcrest.CoreMatchers.equalTo<JsonElement>(patch)
// )
}
@Test
fun childTest() {
test()
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/RemoveOperationTest.kt | 1114709228 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import resources.testdata.TestData_REMOVE
import kotlin.test.Test
/**
* @author ctranxuan (streamdata.io).
*/
class RemoveOperationTest : AbstractTest() {
// @org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_REMOVE)
}
@Test
fun childTest() {
test()
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/ReplaceOperationTest.kt | 706674442 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import resources.testdata.TestData_REPLACE
import kotlin.test.Test
/**
* @author ctranxuan (streamdata.io).
*/
class ReplaceOperationTest : AbstractTest() {
// @org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_REPLACE)
}
@Test
fun childTest() {
test()
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsonDiffTest.kt | 61110586 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import resources.testdata.TestData_SAMPLE
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Unit test
*/
class JsonDiffTest {
var objectMapper = GsonObjectMapper()
lateinit var jsonNode: JsonArray
@BeforeTest
fun setUp() {
jsonNode = objectMapper.readTree(TestData_SAMPLE).jsonArray
}
@Test
fun testSampleJsonDiff() {
for (i in 0 until jsonNode.size) {
val first: JsonElement = jsonNode.get(i).jsonObject.get("first")!!
val second: JsonElement = jsonNode.get(i).jsonObject.get("second")!!
println("Test # $i")
println(first)
println(second)
val actualPatch: JsonElement = JsonDiff.asJson(first, second)
println(actualPatch)
val secondPrime: JsonElement = JsonPatch.apply(actualPatch, first)
println(secondPrime)
assertEquals(second, secondPrime)
}
}
@Test
fun testGeneratedJsonDiff() {
for (i in 0..999) {
val first: JsonElement = TestDataGenerator.generate((0..10).random())
val second: JsonElement = TestDataGenerator.generate((0..10).random())
val actualPatch: JsonElement = JsonDiff.asJson(first, second)
println("Test # $i")
println(first)
println(second)
println(actualPatch)
val secondPrime: JsonElement = JsonPatch.apply(actualPatch, first)
println(secondPrime)
assertEquals(second, secondPrime)
}
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/Rfc6902SamplesTest.kt | 1024784582 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import resources.testdata.TestData_RFC6902_SAMPLES
import kotlin.test.Test
/**
* @author ctranxuan (streamdata.io).
*/
class Rfc6902SamplesTest : AbstractTest() {
// @org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_RFC6902_SAMPLES)
}
@Test
fun childTest() {
test()
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/utils/IOUtils.kt | 4134293767 | package com.reidsync.kxjsonpatch.utils
object IOUtils {
//see http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
fun toString(fileName: String): String {
return fileName
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/utils/GsonObjectMapper.kt | 1787627284 | package com.reidsync.kxjsonpatch.utils
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
class GsonObjectMapper {
fun readTree(jsondata: String?): JsonElement {
if (jsondata != null) {
return Json.parseToJsonElement(jsondata)
}
else {
return JsonNull
}
}
} |
kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsLibSamplesTest.kt | 2365177078 | /*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import resources.testdata.TestData_JS_LIB_SAMPLES
import kotlin.test.Test
/**
* @author ctranxuan (streamdata.io).
*
* These tests comes from JS JSON-Patch libraries (
* https://github.com/Starcounter-Jack/JSON-Patch/blob/master/test/spec/json-patch-tests/tests.json
* https://github.com/cujojs/jiff/blob/master/test/json-patch-tests/tests.json)
*/
class JsLibSamplesTest : AbstractTest() {
//@org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_JS_LIB_SAMPLES)
}
@Test
fun childTest() {
test()
}
} |