path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Collections/Fold/src/Task.kt
|
tinglu
| 248,078,448 | false | null |
// Return the set of products that were ordered by all customers
fun Shop.getProductsOrderedByAll(): Set<Product> {
val allOrderedProducts = customers.flatMap(Customer::getOrderedProducts).toSet()
return customers.fold(allOrderedProducts, { orderedByAllCustomers, customer ->
orderedByAllCustomers.intersect(customer.getOrderedProducts())
})
}
fun Customer.getOrderedProducts(): List<Product> = orders.flatMap(Order::products)
| 0 |
Kotlin
|
0
| 0 |
1892dc22a4f8e85cb0a250142dfe8e1cb4dd7ddc
| 448 |
kotlin-koans
|
MIT License
|
capy/src/test/java/com/jocmp/capy/opml/OPMLImporterTest.kt
|
jocmp
| 610,083,236 | false |
{"Kotlin": 674590, "Ruby": 1236, "Makefile": 1211}
|
package com.jocmp.capy.opml
import com.jocmp.capy.Account
import com.jocmp.capy.InMemoryDatabaseProvider
import com.jocmp.capy.MockFeedFinder
import com.jocmp.capy.accounts.LocalAccountDelegate
import com.jocmp.capy.db.Database
import com.jocmp.capy.fixtures.AccountFixture
import com.jocmp.capy.fixtures.GenericFeed
import com.jocmp.capy.testFile
import com.jocmp.feedfinder.parser.Feed
import io.mockk.mockk
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.last
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import okhttp3.OkHttpClient
import org.junit.Before
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class OPMLImporterTest {
@JvmField
@Rule
val folder = TemporaryFolder()
private val accountID = "777"
private lateinit var account: Account
private lateinit var database: Database
private val httpClient = mockk<OkHttpClient>()
private val sites = listOf<Feed>(
GenericFeed(name = "Daring Fireball", url = "https://daringfireball.net/feeds/main"),
GenericFeed(
name = "BBC News - World",
url = "https://feeds.bbci.co.uk/news/world/rss.xml"
),
GenericFeed(name = "NetNewsWire", url = "https://netnewswire.blog/feed.xml"),
GenericFeed(name = "Block Club Chicago", url = "https://blockclubchicago.org/feed/"),
GenericFeed(name = "<NAME>", url = "https://jvns.ca/atom.xml")
).associateBy { it.feedURL.toString() }
private val finder = MockFeedFinder(sites)
@Before
fun setup() {
database = InMemoryDatabaseProvider.build(accountID)
val delegate = LocalAccountDelegate(
database = database,
httpClient = httpClient,
feedFinder = finder
)
account = AccountFixture.create(
id = accountID,
database = database,
parentFolder = folder,
accountDelegate = delegate
)
}
@Test
fun `it imports feeds and folders`() = runTest {
val inputStream = testFile("nested_import.xml").inputStream()
OPMLImporter(account).import(inputStream = inputStream)
val topLevelFeeds = account.feeds.first().map { it.title }.toSet()
val newsFeeds = account.folders.first().first().feeds.map { it.title }.toSet()
assertEquals(expected = setOf("Daring Fireball", "<NAME>"), actual = topLevelFeeds)
assertEquals(
expected = setOf("BBC News - World", "NetNewsWire", "Block Club Chicago"),
actual = newsFeeds
)
}
@Test
fun `it handles feeds nested in multiple folders`() = runTest {
val inputStream = testFile("multiple_matching_feeds.xml").inputStream()
OPMLImporter(account).import(inputStream = inputStream)
val topLevelFeeds = account.feeds.first().map { it.title }.toSet()
val folders = account.folders.first()
val appleFeeds = folders.find { it.title == "Apple" }!!.feeds.map { it.title }.toSet()
val blogFeeds = folders.find { it.title == "Blogs" }!!.feeds.map { it.title }.toSet()
val newsFeeds = folders.find { it.title == "News" }!!.feeds.map { it.title }.toSet()
assertEquals(expected = setOf("<NAME>"), actual = topLevelFeeds)
assertEquals(expected = setOf("Daring Fireball"), actual = blogFeeds)
assertEquals(expected = setOf("Daring Fireball"), actual = appleFeeds)
assertEquals(
expected = setOf("BBC News - World", "NetNewsWire", "Block Club Chicago"),
actual = newsFeeds
)
}
}
| 15 |
Kotlin
|
3
| 91 |
f8ac7e8c4a6fccfe8f26f1b492261a4f5ce7dafa
| 3,737 |
capyreader
|
MIT License
|
src/leetcode/mayChallenge2020/weektwo/RemoveKDigits.kt
|
adnaan1703
| 268,060,522 | false | null |
package leetcode.mayChallenge2020.weektwo
import utils.println
import java.util.*
fun main() {
removeKdigits("1432219", 3).println()
removeKdigits("10200", 1).println()
removeKdigits("10", 2).println()
}
fun removeKdigits(num: String, k: Int): String {
var limit: Int = k
val stack = Stack<Char>()
num.forEach { char ->
if (stack.isNotEmpty()) {
while (limit > 0 && stack.isNotEmpty() && char < stack.peek()) {
stack.pop()
limit--
}
}
stack.push(char)
}
while (limit > 0 && stack.isNotEmpty()) {
stack.pop()
limit--
}
var ans = ""
var includeZeroes = false
stack.forEach {
if (it != '0')
includeZeroes = true
if (it != '0' || includeZeroes)
ans += it
}
return if (ans.isBlank()) "0" else ans
}
| 0 |
Kotlin
|
0
| 0 |
e81915db469551342e78e4b3f431859157471229
| 893 |
KotlinCodes
|
The Unlicense
|
android/ui/post/src/main/java/any/ui/post/PostUiState.kt
|
dokar3
| 572,488,513 | false | null |
package any.ui.post
import androidx.compose.runtime.Stable
import any.base.model.UiMessage
import any.data.entity.Bookmark
import any.domain.entity.UiContentElement
import any.domain.entity.UiPost
import any.domain.entity.UiServiceManifest
import any.domain.post.ContentSection
@Stable
data class PostUiState(
val service: UiServiceManifest? = null,
val isLoading: Boolean = false,
val loadingProgress: LoadingProgress? = null,
val reversedPages: Boolean = false,
val post: UiPost? = null,
val error: UiMessage.Error? = null,
val isCollected: Boolean = false,
val contentElements: List<UiContentElement> = emptyList(),
val images: List<String> = emptyList(),
val sections: List<ContentSection> = emptyList(),
val bookmarks: List<Bookmark> = emptyList(),
) {
val hasComments = post?.commentsKey != null
val sectionCount = sections.count { !it.isStart && !it.isEnd }
}
data class LoadingProgress(
val value: Float = 0f,
val message: String? = null,
)
| 11 |
Kotlin
|
0
| 9 |
8bffeacfea851380fc9eecb3f5b23c674e47c1da
| 1,012 |
any
|
Apache License 2.0
|
app/src/main/java/ir/hosseinabbasi/cevt/ui/main/IMainActivityInteractor.kt
|
Drjacky
| 140,293,074 | false |
{"Kotlin": 37289}
|
package ir.hosseinabbasi.cevt.ui.main
import ir.hosseinabbasi.cevt.ui.base.IBaseInteractor
/**
* Created by Dr.jacky on 7/9/2018.
*/
interface IMainActivityInteractor : IBaseInteractor
| 0 |
Kotlin
|
0
| 3 |
e120f409c3ea09908172851673233a2661b6d3fb
| 188 |
Cevt
|
The Unlicense
|
poclin/api/src/main/kotlin/poclin/repository/JacksonCodecProvider.kt
|
jaguililla
| 18,274,092 | false | null |
package swatlin.repository
import com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY
import com.fasterxml.jackson.core.JsonParser.Feature.*
import com.fasterxml.jackson.core.util.DefaultIndenter.SYSTEM_LINEFEED_INSTANCE
import com.fasterxml.jackson.databind.DeserializationFeature.*
import com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS
import java.io.IOException
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import io.vertx.core.json.Json
import org.bson.BsonReader
import org.bson.BsonWriter
import org.bson.Document
import org.bson.codecs.Codec
import org.bson.codecs.DecoderContext
import org.bson.codecs.EncoderContext
import org.bson.codecs.configuration.CodecProvider
import org.bson.codecs.configuration.CodecRegistry
import org.bson.types.ObjectId
import kotlin.reflect.KProperty1
import kotlin.reflect.KClass
/**
* Provide codecs that use Jackson Object Mapper for all Java classes.
*/
class JacksonCodecProvider<T : Any, K : Any> internal constructor(
private val type: KClass<T>,
private val key: KProperty1<T, K>) :
CodecProvider {
companion object {
val MAPPER: ObjectMapper = Json.mapper
.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(FAIL_ON_EMPTY_BEANS, false)
.configure(ALLOW_UNQUOTED_FIELD_NAMES, true)
.configure(ALLOW_COMMENTS, true)
.configure(ALLOW_SINGLE_QUOTES, true)
.configure(WRAP_EXCEPTIONS, false)
.configure(FAIL_ON_MISSING_CREATOR_PROPERTIES, false)
.setSerializationInclusion(NON_EMPTY)
.registerModule(Jdk8Module())
.registerModule(JavaTimeModule())
.registerModule(SimpleModule("ObjectIds", Version.unknownVersion())
.addSerializer(ObjectId::class.java, ToStringSerializer())
.addDeserializer(ObjectId::class.java, object : JsonDeserializer<ObjectId>() {
@Throws(IOException::class)
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): ObjectId {
return ObjectId(p.readValueAs(String::class.java))
}
})
)
val WRITER = MAPPER.writer(
DefaultPrettyPrinter().withArrayIndenter(SYSTEM_LINEFEED_INSTANCE)
)
}
/** {@inheritDoc} */
override fun <TC> get(clazz: Class<TC>, registry: CodecRegistry): Codec<TC> {
return object : Codec<TC> {
internal var documentCodec = registry.get(Document::class.java)
/** {@inheritDoc} */
override fun encode(
writer: BsonWriter, value: TC, encoderContext: EncoderContext) {
var map = MAPPER.convertValue(value, Map::class.java) as Map<String, Any>
val generateKey = false//TODO Pass as parameter
if (generateKey) {
val id = if (map[key.name] == null)
ObjectId()
else
ObjectId(map[key.name].toString())
if (clazz == type)
map += key.name to id
}
documentCodec.encode(writer, Document(map), encoderContext)
}
/** {@inheritDoc} */
override fun decode(reader: BsonReader, decoderContext: DecoderContext): TC {
val document = documentCodec.decode(reader, decoderContext)
val generateKey = false//TODO entity.generateKey
if (generateKey)
document.computeIfPresent(key.name) { _, value ->
(value as ObjectId).toHexString()
}
return MAPPER.convertValue(document, clazz)
}
/** {@inheritDoc} */
override fun getEncoderClass(): Class<TC> {
return clazz
}
}
}
}
| 1 | null |
1
| 2 |
a1b110f81c8ce2ef00390c6bf207a7c03f9b9080
| 4,467 |
dojo
|
Apache License 2.0
|
PaperVision/src/main/kotlin/io/github/deltacv/papervision/codegen/language/interpreted/JythonLanguage.kt
|
deltacv
| 421,245,458 | false |
{"Kotlin": 516821, "Java": 6199}
|
package io.github.deltacv.papervision.codegen.language.interpreted
import io.github.deltacv.papervision.codegen.Visibility
import io.github.deltacv.papervision.codegen.build.*
import io.github.deltacv.papervision.codegen.csv
import io.github.deltacv.papervision.codegen.language.Language
import io.github.deltacv.papervision.codegen.language.LanguageBase
object JythonLanguage : LanguageBase(
usesSemicolon = false,
genInClass = false,
optimizeImports = false
) {
override val Parameter.string get() = name
override val trueValue = ConValue(BooleanType, "True")
override val falseValue = ConValue(BooleanType, "False")
override val newImportBuilder = { PythonImportBuilder(this) }
object jarray {
val array = Type("array", "jarray")
val zeros = Type("zeros", "jarray")
}
override fun and(left: Condition, right: Condition) = condition("(${left.value}) and (${right.value})")
override fun or(left: Condition, right: Condition) = condition("(${left.value}) or (${right.value})")
override fun not(condition: Condition) = condition("not (${condition.value})")
override fun instanceVariableDeclaration(
vis: Visibility,
variable: Variable,
label: String?,
isStatic: Boolean,
isFinal: Boolean
) = Pair(
if(label != null) {
"label(\"$label\", \"${variable.name}\")"
} else null,
"${variable.name} = ${variable.variableValue.value}${semicolonIfNecessary()}"
)
override fun localVariableDeclaration(
variable: Variable,
isFinal: Boolean
) = instanceVariableDeclaration(Visibility.PUBLIC, variable).second
override fun instanceVariableSetDeclaration(variable: Variable, v: Value) = "${variable.name} = ${v.value!!}" + semicolonIfNecessary()
override fun streamMatCallDeclaration(id: Value, mat: Value, cvtColor: Value?) =
if(cvtColor != null)
methodCallDeclaration("stream", id, mat, cvtColor)
else methodCallDeclaration("stream", id, mat)
override fun methodDeclaration(
vis: Visibility,
returnType: Type,
name: String,
vararg parameters: Parameter,
isStatic: Boolean,
isFinal: Boolean,
isSynchronized: Boolean,
isOverride: Boolean
): Pair<String?, String> {
return Pair("",
"def $name(${parameters.csv()})"
)
}
override fun ifStatementDeclaration(condition: Condition) = "if ${condition.value}"
override fun forLoopDeclaration(variable: Value, start: Value, max: Value, step: Value?) =
"for ${variable.value} in range(${start.value}, ${max.value}${step?.let { ", $it" } ?: ""})"
override fun foreachLoopDeclaration(variable: Value, iterable: Value) =
"for ${variable.value} in ${iterable.value}"
override fun classDeclaration(
vis: Visibility,
name: String,
body: Scope,
extends: Type?,
vararg implements: Type,
isStatic: Boolean,
isFinal: Boolean
): String {
throw UnsupportedOperationException("Class declarations are not supported in Python")
}
override fun enumClassDeclaration(name: String, vararg values: String): String {
val builder = StringBuilder()
for(value in values) {
builder.append("$value: \"$value\"").appendLine()
}
return """var $name = {
|${builder.toString().trim()}
|}""".trimMargin()
}
override fun castValue(value: Value, castTo: Type) = ConValue(castTo, value.value)
override fun newArrayOf(type: Type, size: Value): ConValue {
val t = when(type) {
BooleanType -> "z"
IntType -> "i"
LongType -> "l"
FloatType -> "f"
DoubleType -> "d"
else -> type.className
}
return ConValue(arrayOf(type), "zeros(${size.value}, $t)").apply {
additionalImports(jarray.zeros)
}
}
override fun arraySize(array: Value) = ConValue(IntType, "len(${array.value})")
override fun block(start: String, body: Scope, tabs: String): String {
val bodyStr = body.get()
return "$tabs${start.trim()}:\n$bodyStr"
}
override fun importDeclaration(importPath: String, className: String) =
throw UnsupportedOperationException("importDeclaration(importPath, className) is not supported in Python")
override fun new(type: Type, vararg parameters: Value) = ConValue(
type, "${type.className}(${parameters.csv()})"
)
override fun nullVal(type: Type) = ConValue(type, "None")
class PythonImportBuilder(val lang: Language) : Language.ImportBuilder {
private val imports = mutableMapOf<String, MutableList<String>>()
override fun import(type: Type) {
val actualType = type.actualImport ?: type
if(lang.isImportExcluded(actualType) || !actualType.shouldImport) return
val classNames = imports[actualType.packagePath]
if(classNames == null) {
imports[actualType.packagePath] = mutableListOf(actualType.className)
} else if(!classNames.contains(actualType.className)){
classNames.add(actualType.className)
}
}
override fun build(): String {
val builder = StringBuilder()
for((importPath, classNames) in imports) {
builder.appendLine().append("from $importPath import ")
if(classNames.size > 1) builder.append("(")
for((i, className) in classNames.withIndex()) {
builder.append(className)
if(i != classNames.size -1) builder.append(", ")
}
if(classNames.size > 1) builder.append(")")
}
return builder.toString().trim()
}
}
}
| 0 |
Kotlin
|
2
| 5 |
6b2740e89e46f99d9dd50aed18db7981d5b3895b
| 5,943 |
PaperVision
|
MIT License
|
platform/platform-tests/testSrc/com/intellij/ui/dsl/builder/LabelTest.kt
|
ingokegel
| 72,937,917 | false | null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.impl.interactiveComponent
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JTextField
import kotlin.test.assertEquals
class LabelTest {
@Test
fun testLabelFor() {
val label = JLabel("Label:")
lateinit var component: JTextField
panel {
row(label) {
component = textField().component
}
}
assertEquals(label.labelFor, component)
}
private data class ComponentConfig(val component: JComponent, val expectedLabelFor: JComponent, val expectedInteractive: JComponent)
@Test
fun testStandardComponents() {
val componentsConfigs = mutableListOf<ComponentConfig>()
JBTextField().let {
componentsConfigs.add(ComponentConfig(it, it, it))
}
TextFieldWithBrowseButton().let {
componentsConfigs.add(ComponentConfig(it, it.textField, it.textField))
}
ComponentWithBrowseButton(JTextField(), {}).let {
componentsConfigs.add(ComponentConfig(it, it.childComponent, it.childComponent))
}
for (componentConfig in componentsConfigs) {
val label = JLabel("Label:")
panel {
row(label) {
cell(componentConfig.component)
}
}
assertEquals(label.labelFor, componentConfig.expectedLabelFor)
assertEquals(componentConfig.component.interactiveComponent, componentConfig.expectedInteractive)
}
}
@Test
fun testLabelForProperty() {
val label = JLabel("Label:")
val panel = JPanel()
val textField = JTextField()
panel.add(textField)
panel.putClientProperty(DslComponentProperty.LABEL_FOR, textField)
panel {
row(label) {
cell(panel)
}
}
assertEquals(label.labelFor, textField)
}
@Test
fun testInvalidLabelForProperty() {
val label = JLabel("Label:")
val panel = JPanel()
panel.putClientProperty(DslComponentProperty.LABEL_FOR, "Invalid")
assertThrows<UiDslException> {
panel {
row(label) {
cell(panel)
}
}
}
}
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,485 |
intellij-community
|
Apache License 2.0
|
src/main/kotlin/com/inari/firefly/control/trigger/TriggerSystem.kt
|
AndreasHefti
| 111,598,575 | false |
{"Kotlin": 631236}
|
package com.inari.firefly.control.trigger
import com.inari.firefly.system.component.ComponentSystem
import com.inari.firefly.system.component.SystemComponent
import com.inari.util.aspect.Aspects
object TriggerSystem : ComponentSystem {
override val supportedComponents: Aspects =
SystemComponent.SYSTEM_COMPONENT_ASPECTS.createAspects(Trigger)
@JvmField val trigger = ComponentSystem.createComponentMapping(
Trigger,
nameMapping = true
)
override fun clearSystem() {
trigger.clear()
}
}
| 1 |
Kotlin
|
0
| 9 |
4e45464a546bf490d3351604d8dc2c9f4fc1587f
| 543 |
flyKo
|
Apache License 2.0
|
next/kmp/sys/src/androidMain/kotlin/org/dweb_browser/sys/toast/ToastApi.android.kt
|
BioforestChain
| 594,577,896 | false |
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
|
package org.dweb_browser.sys.toast
import android.view.Gravity
import android.widget.Toast
import org.dweb_browser.core.module.MicroModule
import org.dweb_browser.helper.getAppContextUnsafe
import org.dweb_browser.helper.withMainContext
actual suspend fun showToast(
microModule: MicroModule.Runtime,
text: String, durationType: ToastDurationType, positionType: ToastPositionType
) =
ToastController.showToast(text, durationType, positionType)
object ToastController {
/**
* 由于 SetGravity 的功能在 Build.VERSION_CODES.R 及其以上版本已经无法使用,所以这边需要改为 SnackBar
*/
suspend fun showToast(
text: String,
durationType: ToastDurationType,
positionType: ToastPositionType
) {
val duration = when (durationType) {
ToastDurationType.LONG -> Toast.LENGTH_LONG
else -> Toast.LENGTH_SHORT
}
withMainContext {
Toast.makeText(getAppContextUnsafe(), text, duration).also {
when (positionType) {
ToastPositionType.TOP -> {
it.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 40)
}
ToastPositionType.CENTER -> {
it.setGravity(Gravity.CENTER_VERTICAL or Gravity.CENTER_HORIZONTAL, 0, 0)
}
else -> {}
}
}.show()
}
}
}
| 66 |
Kotlin
|
5
| 20 |
6db1137257e38400c87279f4ccf46511752cd45a
| 1,259 |
dweb_browser
|
MIT License
|
radar-auth/src/main/java/org/radarbase/auth/jwt/JwtTokenVerifier.kt
|
RADAR-base
| 90,646,368 | false |
{"Kotlin": 1000491, "TypeScript": 476028, "HTML": 280734, "Java": 24215, "SCSS": 20166, "Scala": 16198, "JavaScript": 3395, "Dockerfile": 2950, "Shell": 734, "CSS": 425}
|
package org.radarbase.auth.jwt
import com.auth0.jwt.exceptions.JWTDecodeException
import com.auth0.jwt.exceptions.JWTVerificationException
import com.auth0.jwt.exceptions.SignatureVerificationException
import com.auth0.jwt.interfaces.Claim
import com.auth0.jwt.interfaces.DecodedJWT
import com.auth0.jwt.interfaces.JWTVerifier
import org.radarbase.auth.authentication.TokenVerifier
import org.radarbase.auth.authorization.AuthorityReference
import org.radarbase.auth.authorization.RoleAuthority
import org.radarbase.auth.token.DataRadarToken
import org.radarbase.auth.token.RadarToken
import org.slf4j.LoggerFactory
class JwtTokenVerifier(
private val algorithm: String,
private val verifier: JWTVerifier,
) : TokenVerifier {
override fun verify(token: String): RadarToken = try {
val jwt = verifier.verify(token)
// Do not print full token with signature to avoid exposing valid token in logs.
logger.debug("Verified JWT header {} and payload {}", jwt.header, jwt.payload)
jwt.toRadarToken()
} catch (ex: Throwable) {
when (ex) {
is SignatureVerificationException -> logger.debug("Client presented a token with an incorrect signature.")
is JWTVerificationException -> logger.debug("Verifier {} did not accept token: {}", verifier.javaClass, ex.message)
}
throw ex
}
override fun toString(): String = "JwtTokenVerifier(algorithm=$algorithm)"
companion object {
private val logger = LoggerFactory.getLogger(JwtTokenVerifier::class.java)
const val AUTHORITIES_CLAIM = "authorities"
const val ROLES_CLAIM = "roles"
const val SCOPE_CLAIM = "scope"
const val SOURCES_CLAIM = "sources"
const val GRANT_TYPE_CLAIM = "grant_type"
const val CLIENT_ID_CLAIM = "client_id"
const val USER_NAME_CLAIM = "user_name"
fun DecodedJWT.toRadarToken(): RadarToken {
val claims = claims
return DataRadarToken(
roles = claims.parseRoles(),
scopes = claims.stringListClaim(SCOPE_CLAIM)?.toSet() ?: emptySet(),
sources = claims.stringListClaim(SOURCES_CLAIM) ?: emptyList(),
grantType = claims.stringClaim(GRANT_TYPE_CLAIM),
subject = subject,
issuedAt = issuedAtAsInstant,
expiresAt = expiresAtAsInstant,
audience = audience ?: emptyList(),
token = token,
issuer = issuer,
type = type,
clientId = claims.stringClaim(CLIENT_ID_CLAIM),
username = claims.stringClaim(USER_NAME_CLAIM),
)
}
fun Map<String, Claim?>.stringListClaim(name: String): List<String>? {
val claim = get(name) ?: return null
val claimList = try {
claim.asList(String::class.java)
} catch (ex: JWTDecodeException) {
// skip
null
}
val claims = claimList
?: claim.asString()?.split(' ')
?: return null
return claims.mapNotNull { it?.trimNotEmpty() }
}
fun Map<String, Claim?>.stringClaim(name: String): String? = get(name)?.asString()
?.trimNotEmpty()
private fun String.trimNotEmpty(): String? = trim()
.takeIf { it.isNotEmpty() }
private fun Map<String, Claim?>.parseRoles(): Set<AuthorityReference> = buildSet {
stringListClaim(AUTHORITIES_CLAIM)?.forEach {
val role = RoleAuthority.valueOfAuthorityOrNull(it)
if (role?.scope == RoleAuthority.Scope.GLOBAL) {
add(AuthorityReference(role))
}
}
stringListClaim(ROLES_CLAIM)?.forEach { input ->
val v = input.split(':')
try {
add(
if (v.size == 1 || v[1].isEmpty()) {
AuthorityReference(v[0])
} else {
AuthorityReference(v[1], v[0])
}
)
} catch (ex: IllegalArgumentException) {
// skip
}
}
}
}
}
| 85 |
Kotlin
|
16
| 21 |
7d5d527beaf6e9d20f7f8bb95dfc110eb46fe300
| 4,331 |
ManagementPortal
|
Apache License 2.0
|
app/src/main/java/com/srg/pruebamarvel/data/features/characters/models/CharacterAppearanceItemApiModel.kt
|
sebrodgar
| 342,294,275 | false |
{"Kotlin": 91857}
|
package com.srg.pruebamarvel.data.features.characters.models
/**
* Created by sebrodgar on 07/03/2021.
*/
class CharacterAppearanceItemApiModel(
val resourceURI: String?,
val name: String?,
val type: String?
) {
}
| 0 |
Kotlin
|
0
| 0 |
bfec1d716283ee8a7d638391be6272509f2064f0
| 229 |
code-test-marvel
|
Apache License 2.0
|
app/src/main/java/com/xuanlocle/weatherapp/ui/base/BaseViewModel.kt
|
xuanlocle
| 391,120,213 | false | null |
package com.xuanlocle.weatherapp.ui.base
import androidx.lifecycle.ViewModel
import com.xuanlocle.weatherapp.data.remote.response.ErrorResponse
import com.xuanlocle.weatherapp.widget.MutableLiveDataSingle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlin.coroutines.CoroutineContext
abstract class BaseViewModel : ViewModel() {
private lateinit var job: Job
protected lateinit var uiScope: CoroutineScope
protected lateinit var ioContext: CoroutineContext
val showError = MutableLiveDataSingle<ErrorResponse>()
fun init() {
onCreate()
}
protected open fun onCreate() {
job = Job()
uiScope = CoroutineScope(Dispatchers.Main + job)
ioContext = Dispatchers.IO + job
}
fun onDestroy() {
uiScope.cancel()
ioContext.cancel()
}
open fun showLoading(){
}
open fun hideLoading() {
}
}
| 0 |
Kotlin
|
0
| 4 |
8cbd5c792750de2a70430e3b37833c9bfb68b3b2
| 996 |
WeatherApp
|
MIT License
|
app/src/main/java/pl/valueadd/mvi/example/presentation/main/first/FirstViewState.kt
|
valueadd-poland
| 238,159,445 | false | null |
package pl.valueadd.mvi.example.presentation.main.first
import kotlinx.android.parcel.Parcelize
import org.apache.commons.lang3.StringUtils.EMPTY
import org.apache.commons.lang3.math.NumberUtils.INTEGER_ZERO
import pl.valueadd.mvi.IBaseViewState
import pl.valueadd.mvi.presenter.IBasePartialState
@Parcelize
data class FirstViewState(
val count: Int = INTEGER_ZERO,
val error: String = EMPTY,
val value: String = EMPTY
) : IBaseViewState {
sealed class PartialState :
IBasePartialState {
data class ProcessDataSuccess(val value: String) : PartialState()
data class ProcessDataFail(val error: Throwable) : PartialState()
data class ChangeCountSuccess(val count: Int) : PartialState()
data class ChangeCountFail(val error: Throwable) : PartialState()
}
}
| 6 |
Kotlin
|
0
| 3 |
7d52819415c10e85dc6806d41433ad7ced63b5e9
| 815 |
mvi-valueadd
|
Apache License 2.0
|
BrenMkOnline/app/src/main/java/com/brenhr/mkonline/util/OrderParser.kt
|
brenhr
| 519,068,116 | false | null |
package com.brenhr.mkonline.util
import com.brenhr.mkonline.model.Order
import com.google.firebase.firestore.DocumentSnapshot
class OrderParser {
fun parse(document: DocumentSnapshot): Order {
val id = document.id
val status = document.data?.get("status") as String
val quantity = document.data?.get("quantity") as Long
val total = document.data?.get("total") as Long
return Order(id, status, quantity, total)
}
}
| 0 |
Kotlin
|
0
| 0 |
b0828728a29342f0b0a02e123e0b8c38de4c2e25
| 465 |
android-bren-mk
|
Apache License 2.0
|
embrace-android-sdk/src/integrationTest/kotlin/io/embrace/android/embracesdk/testcases/session/BackgroundActivityDisabledTest.kt
|
embrace-io
| 704,537,857 | false |
{"Kotlin": 2970383, "C": 189341, "Java": 162931, "C++": 13140, "CMake": 4261}
|
package io.embrace.android.embracesdk.testcases.session
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.embrace.android.embracesdk.assertions.findEventsOfType
import io.embrace.android.embracesdk.assertions.findSessionSpan
import io.embrace.android.embracesdk.assertions.getSessionId
import io.embrace.android.embracesdk.fakes.FakeClock
import io.embrace.android.embracesdk.fakes.injection.FakeInitModule
import io.embrace.android.embracesdk.fakes.injection.FakeWorkerThreadModule
import io.embrace.android.embracesdk.internal.arch.schema.EmbType
import io.embrace.android.embracesdk.internal.clock.nanosToMillis
import io.embrace.android.embracesdk.internal.opentelemetry.embCleanExit
import io.embrace.android.embracesdk.internal.opentelemetry.embColdStart
import io.embrace.android.embracesdk.internal.opentelemetry.embProcessIdentifier
import io.embrace.android.embracesdk.internal.opentelemetry.embSequenceId
import io.embrace.android.embracesdk.internal.opentelemetry.embSessionEndType
import io.embrace.android.embracesdk.internal.opentelemetry.embSessionNumber
import io.embrace.android.embracesdk.internal.opentelemetry.embSessionStartType
import io.embrace.android.embracesdk.internal.opentelemetry.embState
import io.embrace.android.embracesdk.internal.opentelemetry.embTerminated
import io.embrace.android.embracesdk.internal.payload.ApplicationState
import io.embrace.android.embracesdk.internal.payload.Span
import io.embrace.android.embracesdk.internal.spans.findAttributeValue
import io.embrace.android.embracesdk.internal.worker.Worker
import io.embrace.android.embracesdk.spans.EmbraceSpan
import io.embrace.android.embracesdk.testframework.IntegrationTestRule
import io.embrace.android.embracesdk.testframework.actions.EmbraceActionInterface
import io.embrace.android.embracesdk.testframework.actions.EmbraceSetupInterface
import io.embrace.android.embracesdk.testframework.assertions.assertMatches
import io.embrace.android.embracesdk.testframework.assertions.getLastLog
import io.opentelemetry.semconv.incubating.SessionIncubatingAttributes
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Verify functionality of the SDK if background activities are disabled
*/
@RunWith(AndroidJUnit4::class)
internal class BackgroundActivityDisabledTest {
@Rule
@JvmField
val testRule: IntegrationTestRule = IntegrationTestRule {
val clock = FakeClock()
val initModule = FakeInitModule(clock)
val workerThreadModule =
FakeWorkerThreadModule(initModule, Worker.Background.LogMessageWorker)
EmbraceSetupInterface(
overriddenClock = clock,
overriddenInitModule = initModule,
overriddenWorkerThreadModule = workerThreadModule,
).apply {
overriddenConfigService.backgroundActivityCaptureEnabled = false
}
}
@Test
fun `recording telemetry in the background when background activity is disabled does the right thing`() {
var traceStopMs: Long = -1
lateinit var trace: EmbraceSpan
testRule.runTest(
testCaseAction = {
recordSession {
trace = checkNotNull(embrace.startSpan("test-trace"))
}
runLoggingThread()
traceStopMs = clock.tick(100L)
assertTrue(trace.stop())
// Check what should and shouldn't be logged when there is no background activity and the app is in the background
assertTrue(embrace.isStarted)
assertTrue(embrace.currentSessionId.isNullOrBlank())
assertTrue(embrace.deviceId.isNotBlank())
assertNull(embrace.startSpan("test"))
embrace.logError("error")
flushLogEnvelope()
embrace.addBreadcrumb("not-logged")
clock.tick(10_000L)
embrace.logInfo("info")
flushLogEnvelope()
recordSession {
assertFalse(embrace.currentSessionId.isNullOrBlank())
embrace.addBreadcrumb("logged")
embrace.logWarning("warning")
flushLogEnvelope()
embrace.logError("sent-after-session")
}
flushLogEnvelope()
},
assertAction = {
val sessions = getSessionEnvelopes(2)
getSessionEnvelopes(0, ApplicationState.BACKGROUND)
val logs = getLogEnvelopes(4).map { it.getLastLog() }
with(logs[0]) {
assertEquals("error", body)
attributes?.assertMatches {
embState.attributeKey.key to "background"
}
assertNull(attributes?.findAttributeValue(SessionIncubatingAttributes.SESSION_ID.key))
}
with(logs[1]) {
assertEquals("info", body)
attributes?.assertMatches {
embState.attributeKey.key to "background"
}
assertNull(attributes?.findAttributeValue(SessionIncubatingAttributes.SESSION_ID.key))
}
with(logs[2]) {
assertEquals("warning", body)
attributes?.assertMatches {
embState.attributeKey.key to "foreground"
SessionIncubatingAttributes.SESSION_ID.key to sessions[0].getSessionId()
}
}
val secondSession = sessions[1]
assertEquals(
0,
getSessionEnvelopes(0, ApplicationState.BACKGROUND).size
)
with(logs[3]) {
assertEquals("sent-after-session", body)
attributes?.assertMatches {
embState.attributeKey.key to "foreground"
SessionIncubatingAttributes.SESSION_ID.key to secondSession.getSessionId()
}
}
with(secondSession) {
with(findSessionSpan()) {
with(findEventsOfType(EmbType.System.Breadcrumb)) {
assertEquals(1, size)
single().attributes?.assertMatches {
"message" to "logged"
}
}
}
with(checkNotNull(data.spans?.find { it.name == "test-trace" })) {
assertEquals(traceStopMs, endTimeNanos?.nanosToMillis())
}
}
}
)
}
private fun EmbraceActionInterface.flushLogEnvelope() {
runLoggingThread()
clock.tick(2000L)
flushLogBatch()
}
@Test
fun `session span and payloads structurally correct`() {
var session1StartMs: Long = -1
var session1EndMs: Long = -1
var session2StartMs: Long = -1
var session2EndMs: Long = -1
testRule.runTest(
testCaseAction = {
session1StartMs = clock.now()
recordSession()
session1EndMs = clock.now()
session2StartMs = clock.tick(15000)
recordSession()
session2EndMs = clock.now()
},
assertAction = {
val sessions = getSessionEnvelopes(2)
val session1 = sessions[0]
val session2 = sessions[1]
assertEquals(2, sessions.size)
assertEquals(0, getSessionEnvelopes(0, ApplicationState.BACKGROUND).size)
assertEquals(session1.metadata, session2.metadata)
assertEquals(
session1.resource?.copy(screenResolution = null, jailbroken = null),
session2.resource?.copy(screenResolution = null, jailbroken = null)
)
assertEquals(session1.version, session2.version)
assertEquals(session1.type, session2.type)
val sessionSpan1 = session1.findSessionSpan()
val sessionSpan2 = session2.findSessionSpan()
sessionSpan1.assertExpectedSessionSpanAttributes(
startMs = session1StartMs,
endMs = session1EndMs,
sessionNumber = 1,
sequenceId = 1,
coldStart = true,
)
sessionSpan2.assertExpectedSessionSpanAttributes(
startMs = session2StartMs,
endMs = session2EndMs,
sessionNumber = 2,
sequenceId = 4,
coldStart = false,
)
assertNotEquals(
sessionSpan1.attributes?.findAttributeValue(SessionIncubatingAttributes.SESSION_ID.key),
sessionSpan2.attributes?.findAttributeValue(SessionIncubatingAttributes.SESSION_ID.key)
)
assertEquals(
sessionSpan1.attributes?.findAttributeValue(embProcessIdentifier.attributeKey.key),
sessionSpan2.attributes?.findAttributeValue(embProcessIdentifier.attributeKey.key)
)
}
)
}
private fun runLoggingThread() {
(testRule.setup.overriddenWorkerThreadModule as FakeWorkerThreadModule).executor.runCurrentlyBlocked()
}
private fun flushLogBatch() {
testRule.bootstrapper.logModule.logOrchestrator.flush(false)
}
private fun Span.assertExpectedSessionSpanAttributes(
startMs: Long,
endMs: Long,
sessionNumber: Int,
sequenceId: Int,
coldStart: Boolean,
) {
assertEquals(startMs, startTimeNanos?.nanosToMillis())
assertEquals(endMs, endTimeNanos?.nanosToMillis())
attributes?.assertMatches {
embSessionNumber.attributeKey.key to sessionNumber
embSequenceId.attributeKey.key to sequenceId
embColdStart.attributeKey.key to coldStart
embState.attributeKey.key to "foreground"
embCleanExit.attributeKey.key to "true"
embTerminated.attributeKey.key to "false"
embSessionStartType.attributeKey.key to "state"
embSessionEndType.attributeKey.key to "state"
}
with(checkNotNull(attributes)) {
assertFalse(findAttributeValue(embProcessIdentifier.attributeKey.key).isNullOrBlank())
assertFalse(findAttributeValue(SessionIncubatingAttributes.SESSION_ID.key).isNullOrBlank())
}
}
}
| 25 |
Kotlin
|
11
| 134 |
459e961f6b722fee3247520b3688a5c54723559b
| 10,984 |
embrace-android-sdk
|
Apache License 2.0
|
app/src/main/java/com/example/project_001/AccountSettingsMainActivity2.kt
|
bagash23
| 434,772,890 | false | null |
package com.example.project_001
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.media.Image
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.example.project_001.Model.User
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.StorageTask
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.Picasso
import com.theartofdev.edmodo.cropper.CropImage
class AccountSettingsMainActivity2 : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private var checker = ""
private var myUrl = ""
private var imageUri: Uri? = null
private var storageProfilePicker: StorageReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_settings_main2)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
storageProfilePicker = FirebaseStorage.getInstance().reference.child("Profile Pictures")
findViewById<Button>(R.id.logout_btn).setOnClickListener {
FirebaseAuth.getInstance().signOut()
val intent = Intent(this@AccountSettingsMainActivity2, SigninMainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
findViewById<TextView>(R.id.change_image_text_btn).setOnClickListener {
checker = "clicked"
CropImage.activity()
.setAspectRatio(1,1)
.start(this@AccountSettingsMainActivity2)
}
findViewById<ImageView>(R.id.save_info_profile_btn).setOnClickListener {
if (checker == "clicked"){
uploadImageAndUpdateInfo()
}else{
updateUserInfoOnly()
}
}
userInfo()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null)
{
val result = CropImage.getActivityResult(data)
imageUri = result.uri
findViewById<ImageView>(R.id.profile_image_view_profile_frag).setImageURI(imageUri)
}
}
private fun updateUserInfoOnly() {
when {
TextUtils.isEmpty(findViewById<TextView>(R.id.full_name_profile_frag).text.toString()) -> {
Toast.makeText(this, "Please write full name first", Toast.LENGTH_LONG)
}
findViewById<TextView>(R.id.username_profile_frag).text.toString() == "" -> {
Toast.makeText(this, "Please write user name first", Toast.LENGTH_LONG)
}
findViewById<TextView>(R.id.bio_profile_frag).text.toString() == "" -> {
Toast.makeText(this, "Please write bio first", Toast.LENGTH_LONG)
}
else -> {
val usersRef = FirebaseDatabase.getInstance().reference.child("Users")
val usersMap = HashMap<String, Any>()
usersMap["fullname"] = findViewById<TextView>(R.id.full_name_profile_frag).text.toString().toLowerCase()
usersMap["username"] = findViewById<TextView>(R.id.username_profile_frag).text.toString().toLowerCase()
usersMap["bio"] = findViewById<TextView>(R.id.bio_profile_frag).text.toString().toLowerCase()
usersRef.child(firebaseUser.uid).updateChildren(usersMap)
Toast.makeText(this, "Account Information has been successfully", Toast.LENGTH_LONG)
val intent = Intent(this@AccountSettingsMainActivity2, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
private fun userInfo(){
val usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.uid)
usersRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val user = snapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getImage()).placeholder(R.drawable.profile).into(findViewById<ImageView>(R.id.profile_image_view_profile_frag))
findViewById<TextView>(R.id.username_profile_frag).setText(user!!.getUsername())
findViewById<TextView>(R.id.full_name_profile_frag).setText(user!!.getFullname())
findViewById<TextView>(R.id.bio_profile_frag).setText(user!!.getBio())
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun uploadImageAndUpdateInfo() {
when{
imageUri == null -> Toast.makeText(this, "Please select image firs", Toast.LENGTH_LONG)
TextUtils.isEmpty(findViewById<TextView>(R.id.full_name_profile_frag).text.toString()) -> {
Toast.makeText(this, "Please write full name first", Toast.LENGTH_LONG)
}
findViewById<TextView>(R.id.username_profile_frag).text.toString() == "" -> {
Toast.makeText(this, "Please write user name first", Toast.LENGTH_LONG)
}
findViewById<TextView>(R.id.bio_profile_frag).text.toString() == "" -> {
Toast.makeText(this, "Please write bio first", Toast.LENGTH_LONG)
}
else -> {
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Account Settings")
progressDialog.setMessage("Please wait, we are updating your profile...")
progressDialog.show()
val fileref = storageProfilePicker!!.child(firebaseUser!!.uid + ".jpg")
var uploadTask: StorageTask<*>
uploadTask = fileref.putFile(imageUri!!)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (task.isSuccessful){
task.exception?.let {
throw it
progressDialog.dismiss()
}
}
return@Continuation fileref.downloadUrl
}).addOnCompleteListener ( OnCompleteListener<Uri>{task ->
if (task.isSuccessful){
val downloadUri = task.result
myUrl = downloadUri.toString()
val ref = FirebaseDatabase.getInstance().reference.child("Users")
val usersMap = HashMap<String, Any>()
usersMap["fullname"] = findViewById<TextView>(R.id.full_name_profile_frag).text.toString().toLowerCase()
usersMap["username"] = findViewById<TextView>(R.id.username_profile_frag).text.toString().toLowerCase()
usersMap["bio"] = findViewById<TextView>(R.id.bio_profile_frag).text.toString().toLowerCase()
usersMap["image"] = myUrl
ref.child(firebaseUser.uid).updateChildren(usersMap)
Toast.makeText(this, "Account Information has been successfully", Toast.LENGTH_LONG)
val intent = Intent(this@AccountSettingsMainActivity2, MainActivity::class.java)
startActivity(intent)
finish()
progressDialog.dismiss()
}
else{
progressDialog.dismiss()
}
} )
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
d7b121ae4606b2891df0c8037482337dab1c4d85
| 8,624 |
clone-app
|
Apache License 2.0
|
ggdsl-echarts/src/main/kotlin/org/jetbrains/kotlinx/ggdsl/echarts/features/animation/PlotChangeAnimation.kt
|
Kotlin
| 502,039,936 | false | null |
/*
* Copyright 2020-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.ggdsl.echarts.features.animation
import org.jetbrains.kotlinx.ggdsl.ir.Plot
public data class PlotChangeAnimation(val plots: List<Plot>, val interval: Int)
| 48 |
Kotlin
|
1
| 44 |
8a161098d0d946c28bde3cf3c7bea6a1eeba073c
| 297 |
ggdsl
|
Apache License 2.0
|
profilers/testSrc/com/android/tools/profilers/leakcanary/LeakCanaryModelTest.kt
|
JetBrains
| 60,701,247 | false |
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
|
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.tools.profilers.leakcanary
import com.android.testutils.TestUtils
import com.android.tools.adtui.model.FakeTimer
import com.android.tools.idea.transport.faketransport.FakeGrpcChannel
import com.android.tools.idea.transport.faketransport.FakeTransportService
import com.android.tools.idea.transport.faketransport.commands.CommandHandler
import com.android.tools.profiler.proto.Commands
import com.android.tools.profiler.proto.Common
import com.android.tools.profiler.proto.LeakCanary
import com.android.tools.profilers.FakeIdeProfilerServices
import com.android.tools.profilers.ProfilerClient
import com.android.tools.profilers.StudioProfilers
import com.android.tools.profilers.WithFakeTimer
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
class LeakCanaryModelTest : WithFakeTimer {
override val timer = FakeTimer()
private val transportService = FakeTransportService(timer)
@Rule
@JvmField
val grpcChannel = FakeGrpcChannel("LeakCanaryModelTestChannel", transportService)
private lateinit var profilers: StudioProfilers
private lateinit var stage: LeakCanaryModel
private lateinit var ideProfilerServices: FakeIdeProfilerServices
@Before
fun setup() {
ideProfilerServices = FakeIdeProfilerServices()
profilers = StudioProfilers(ProfilerClient(grpcChannel.channel), ideProfilerServices, timer)
stage = LeakCanaryModel(profilers)
}
@Test
fun `Leak canary stage enter - success case with multiple events`() {
transportService.setCommandHandler(Commands.Command.CommandType.START_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf(
"SingleApplicationLeak.txt",
"SingleApplicationLeakAnalyzeCmd.txt",
"MultiApplicationLeak.txt",
"NoLeak.txt"
)))
transportService.setCommandHandler(Commands.Command.CommandType.STOP_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf()))
stage.startListening()
// Wait for listener to receive events
timer.tick(FakeTimer.ONE_SECOND_IN_NS)
// Verify leak events
assertEquals(4, stage.leakEvents.size) // 4 events are sent
assertEquals(4, stage.leaksDetectedCount.value) // All 4 events triggered a leak detected event
stage.stopListening()
// After stage exit we get all events
assertEquals(4, stage.leakEvents.size) // 4 events are sent
assertEquals(4, stage.leaksDetectedCount.value) // All 4 events triggered a leak detected event
}
@Test
fun `Leak canary stage enter - Invalid leaks are skipped`() {
transportService.setCommandHandler(Commands.Command.CommandType.START_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf(
"SingleApplicationLeak.txt",
"InValidLeak.txt"
)))
transportService.setCommandHandler(Commands.Command.CommandType.STOP_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf()))
stage.startListening()
// Wait for listener to receive events
timer.tick(FakeTimer.ONE_SECOND_IN_NS)
// Verify leakEvents
assertEquals(1, stage.leakEvents.size) // 1 event is sent
assertEquals(1, stage.leaksDetectedCount.value) // 1 event triggered a leak detected event
stage.stopListening()
// After stage exit we get all events
assertEquals(1, stage.leakEvents.size) // 1 event are sent
assertEquals(1, stage.leaksDetectedCount.value) // 1 event triggered a leak detected event
}
@Test
fun `Leak canary stage enter - no leak events`() {
transportService.setCommandHandler(Commands.Command.CommandType.START_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf()))
transportService.setCommandHandler(Commands.Command.CommandType.STOP_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf()))
stage.startListening()
// Wait for the listener to receive events
timer.tick(FakeTimer.ONE_SECOND_IN_NS)
// Verify leakEvents
assertEquals(0, stage.leakEvents.size) // No events are sent
assertEquals(0, stage.leaksDetectedCount.value) // No leak detected event
stage.stopListening()
// After stage exit we get all events
assertEquals(0, stage.leakEvents.size) // No events are sent
assertEquals(0, stage.leaksDetectedCount.value) // No leak detected event
}
@Test
fun `Leak canary stage enter - all leaks detected are not valid`() {
transportService.setCommandHandler(Commands.Command.CommandType.START_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf(
"InValidLeak.txt",
"InValidLeak.txt",
"InValidLeak.txt",
"InValidLeak.txt"
)))
transportService.setCommandHandler(Commands.Command.CommandType.STOP_LOGCAT_TRACKING,
FakeLeakCanaryCommandHandler(timer, profilers, listOf()))
stage.startListening()
// Wait for listener to receive events
timer.tick(FakeTimer.ONE_SECOND_IN_NS)
// Verify leakEvents
assertEquals(0, stage.leakEvents.size) // 0 event are sent
assertEquals(0, stage.leaksDetectedCount.value) // No event triggered leak detected event
stage.stopListening()
// After stage exit we get all events
assertEquals(0, stage.leakEvents.size) // 0 event are sent
assertEquals(0, stage.leaksDetectedCount.value) // No event triggered leak detected event
}
}
class FakeLeakCanaryCommandHandler(timer: FakeTimer,
val profilers: StudioProfilers,
val leaksToSendFiles: List<String>) : CommandHandler(timer) {
override fun handleCommand(command: Commands.Command,
events: MutableList<Common.Event>) {
leaksToSendFiles.forEach {leakToSendFile ->
events.add(getLeakCanaryEvent(profilers, leakToSendFile))
}
}
companion object {
const val TEST_DATA_PATH = "tools/adt/idea/profilers/testData/sampleLeaks/"
fun getLeakCanaryEvent(profilers: StudioProfilers, leakToSendFile: String): Common.Event {
val file = TestUtils.resolveWorkspacePath("${TEST_DATA_PATH}/$leakToSendFile").toFile()
val fileContent = file.readText()
return Common.Event.newBuilder()
.setGroupId(profilers.session.pid.toLong())
.setPid(profilers.session.pid)
.setKind(Common.Event.Kind.LEAKCANARY_LOGCAT)
.setLeakcanaryLogcat(LeakCanary.LeakCanaryLogcatData
.newBuilder()
.setLogcatMessage(fileContent).build())
.setTimestamp(System.nanoTime())
.build()
}
}
}
| 5 |
Kotlin
|
227
| 948 |
10110983c7e784122d94c7467e9d243aba943bf4
| 7,932 |
android
|
Apache License 2.0
|
app/src/main/java/com/coppel/preconfirmar/entities/ActualizarTipoParcial.kt
|
Aguayo91
| 394,428,141 | false | null |
package com.coppel.preconfirmar.entities
data class ActualizarTipoParcial(
val state: Int = -5,
val message: String = "",
val data: Any?
)
| 0 |
Kotlin
|
0
| 0 |
17880cc61f72229b0b8ed8f87afa560877234097
| 152 |
Christian
|
MIT License
|
network/core/src/commonMain/kotlin/co/yml/network/core/parser/BasicDataParserFactory.kt
|
yml-org
| 504,124,065 | false | null |
package co.yml.network.core.parser
import co.yml.network.core.Headers
import co.yml.network.core.MimeType
import co.yml.network.core.request.RequestPath
/**
* Basic implementation of [DataParserFactory] holding a map of [DataParser] w.r.t. it's contentType.
*/
class BasicDataParserFactory(private val parserFactoryMap: Map<String, DataParser>) :
DataParserFactory {
override fun getParser(
contentType: String,
requestPath: RequestPath,
requestHeaders: Headers?,
responseHeaders: Headers?
): DataParser {
val trimmedContentType = contentType.trim()
val key = parserFactoryMap.keys.find { trimmedContentType.startsWith(it) }
return parserFactoryMap[key]
?: throw Exception("No parser specified for $trimmedContentType.")
}
companion object {
fun json(jsonDataParser: DataParser) =
BasicDataParserFactory(mapOf(MimeType.JSON.toString() to jsonDataParser))
}
}
| 1 |
Kotlin
|
2
| 5 |
2b5162b3e687d81546d9c7ce7a666b3a2b6df889
| 977 |
ynetwork-android
|
Apache License 2.0
|
paymentsheet/src/main/java/com/stripe/android/paymentsheet/elements/ResourceRepository.kt
|
stripe
| 6,926,049 | false | null |
package com.stripe.android.paymentsheet.elements
import com.stripe.android.paymentsheet.address.AddressFieldElementRepository
import javax.inject.Inject
import javax.inject.Singleton
/**
* This holds all the resources read in from JSON.
*/
@Singleton
internal class ResourceRepository @Inject internal constructor(
internal val bankRepository: BankRepository,
internal val addressRepository: AddressFieldElementRepository
)
| 54 |
Kotlin
|
502
| 866 |
c64b81095c36df34ffb361da276c116ffd5a2523
| 436 |
stripe-android
|
MIT License
|
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/TrafficLights.kt
|
DevSrSouza
| 311,134,756 | false | null |
package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.TablerIcons
public val TablerIcons.TrafficLights: ImageVector
get() {
if (_trafficLights != null) {
return _trafficLights!!
}
_trafficLights = Builder(name = "TrafficLights", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 2.0f)
lineTo(12.0f, 2.0f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 17.0f, 7.0f)
lineTo(17.0f, 17.0f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 12.0f, 22.0f)
lineTo(12.0f, 22.0f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 7.0f, 17.0f)
lineTo(7.0f, 7.0f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 12.0f, 2.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 7.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 12.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 17.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
}
}
.build()
return _trafficLights!!
}
private var _trafficLights: ImageVector? = null
| 17 | null |
25
| 571 |
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,378 |
compose-icons
|
MIT License
|
app/src/main/java/com/mygomii/koin/example/domain/models/Post.kt
|
mygomii
| 784,098,109 | false |
{"Kotlin": 19118}
|
package com.mygomii.koin.example.domain.models
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Post(
var userId: Int,
var id: Int,
var title: String,
var body: String
)
| 0 |
Kotlin
|
0
| 0 |
9e2a59c13d20a509e5b68c16af190dcddf2c4b7e
| 220 |
koin-example
|
Apache License 2.0
|
app/src/main/java/bj/vinylbrowser/model/labelrelease/RootLabelResponse.kt
|
jbmlaird
| 82,479,889 | false | null |
package bj.vinylbrowser.model.labelrelease
import bj.vinylbrowser.model.common.Pagination
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME> on 19/05/2017.
*/
data class RootLabelResponse(val pagination: Pagination,
@SerializedName("releases") val labelReleases: List<LabelRelease>)
| 3 |
Java
|
1
| 20 |
23facb4e1ab156508e934ebc1fcd1d57b3255aba
| 338 |
DiscogsBrowser
|
MIT License
|
core/src/test/java/com/flexa/identitykit/coppa/CoppaHelperTest.kt
|
flexa
| 843,038,714 | false |
{"Kotlin": 938339}
|
package com.flexa.identity.coppa
import junit.framework.TestCase
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.Calendar
import java.util.TimeZone
@Config(sdk = [28])
@RunWith(RobolectricTestRunner::class)
class CoppaHelperTest {
private val minimumAllowedAge = CoppaHelper.MINIMUM_ALLOWED_AGE
private val utc = TimeZone.getTimeZone("UTC")
private val currentYear = 2021
private val currentDate = Calendar.getInstance().apply {
set(Calendar.YEAR, currentYear)
set(Calendar.MONTH, Calendar.FEBRUARY)
set(Calendar.DAY_OF_MONTH, 17)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
timeZone = utc
}.time
private val olderOrEqual = Calendar.getInstance().apply {
set(Calendar.YEAR, currentYear - minimumAllowedAge)
set(Calendar.MONTH, Calendar.FEBRUARY)
set(Calendar.DAY_OF_MONTH, 17)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
timeZone = utc
}.time
private val younger = Calendar.getInstance().apply {
set(Calendar.YEAR, currentYear - minimumAllowedAge + 1)
set(Calendar.MONTH, Calendar.FEBRUARY)
set(Calendar.DAY_OF_MONTH, 17)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
timeZone = utc
}.time
@Test
fun shouldCalculateDateDifference() {
val start = Calendar.getInstance().apply {
set(Calendar.YEAR, 1900)
set(Calendar.MONTH, Calendar.JANUARY)
set(Calendar.DAY_OF_MONTH, 1)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
timeZone = utc
}
val cal = Calendar.getInstance().apply {
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
timeZone = utc
}
while (cal != start) {
cal.add(Calendar.DAY_OF_MONTH, -1)
cal.set(Calendar.HOUR, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
cal.timeZone = utc
val date = cal.time
val diff1 = CoppaHelper.getYearDiffJoda(date, currentDate)
val diff2 = CoppaHelper.getYearDiff(date, currentDate)
assertEquals(diff1, diff2)
}
}
@Test
fun shouldPassWithOldAndGreater() {
val age = CoppaHelper.getYearDiff(olderOrEqual, currentDate)
TestCase.assertTrue(age >= minimumAllowedAge)
}
@Test
fun shouldFailsWithLessThenRequired() {
val age = CoppaHelper.getYearDiff(younger, currentDate)
TestCase.assertTrue(age < minimumAllowedAge)
}
@Test
fun shouldReturnZeroOnNullDate() {
TestCase.assertEquals(CoppaHelper.getUserAge(null), 0)
}
}
| 0 |
Kotlin
|
0
| 17 |
44c3adc705454424187ccffe93afa47170f87572
| 3,261 |
flexa-android
|
MIT License
|
domain/src/main/java/akio/apps/myrun/domain/tracking/StoreTrackingActivityDataUsecase.kt
|
khoi-nguyen-2359
| 297,064,437 | false |
{"Kotlin": 818250, "Java": 177639}
|
package akio.apps.myrun.domain.tracking
import akio.apps.myrun.data.activity.api.ActivityLocalStorage
import akio.apps.myrun.data.activity.api.model.ActivityDataModel
import akio.apps.myrun.data.activity.api.model.ActivityLocation
import akio.apps.myrun.data.activity.api.model.ActivityType
import akio.apps.myrun.data.activity.api.model.AthleteInfo
import akio.apps.myrun.data.activity.api.model.BaseActivityModel
import akio.apps.myrun.data.activity.api.model.CyclingActivityModel
import akio.apps.myrun.data.activity.api.model.RunningActivityModel
import akio.apps.myrun.data.authentication.api.UserAuthenticationState
import akio.apps.myrun.data.eapps.api.StravaSyncState
import akio.apps.myrun.data.eapps.api.StravaTokenRepository
import akio.apps.myrun.data.location.api.PolyUtil
import akio.apps.myrun.data.tracking.api.RouteTrackingLocationRepository
import akio.apps.myrun.data.tracking.api.RouteTrackingState
import akio.apps.myrun.data.user.api.UnitConverter
import akio.apps.myrun.domain.activity.getLatLng
import akio.apps.myrun.domain.common.ObjectAutoId
import android.graphics.Bitmap
import javax.inject.Inject
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
/**
* Stores all information of an activity that have been tracked. Must not include any data that get
* from server because this works in offline mode.
*/
class StoreTrackingActivityDataUsecase @Inject constructor(
private val userAuthenticationState: UserAuthenticationState,
private val routeTrackingState: RouteTrackingState,
private val routeTrackingLocationRepository: RouteTrackingLocationRepository,
private val activityLocalStorage: ActivityLocalStorage,
private val stravaTokenRepository: StravaTokenRepository,
private val stravaSyncState: StravaSyncState,
private val objectAutoId: ObjectAutoId,
private val polyUtil: PolyUtil,
) {
suspend fun invoke(activityName: String, routeImageBitmap: Bitmap) = coroutineScope {
val userId = userAuthenticationState.requireUserAccountId()
val activityId = objectAutoId.autoId()
val activityLocations = routeTrackingLocationRepository.getAllLocations()
val activityModel =
createActivityInfo(userId, activityId, activityName, activityLocations)
val activityStorageAsync = async {
activityLocalStorage.storeActivityData(
activityModel,
activityLocations,
routeImageBitmap
)
}
val activitySyncAsync = async {
if (stravaSyncState.getStravaSyncAccountId() != null) {
activityLocalStorage.storeActivitySyncData(activityModel, activityLocations)
}
}
activityStorageAsync.join()
activitySyncAsync.join()
}
private suspend fun createActivityInfo(
userId: String,
activityId: String,
activityName: String,
trackedLocations: List<ActivityLocation>,
): BaseActivityModel {
val endTime = System.currentTimeMillis()
val startTime = routeTrackingState.getTrackingStartTime()
val duration = routeTrackingState.getTrackingDuration()
val distance = routeTrackingState.getRouteDistance()
val encodedPolyline = polyUtil.encode(trackedLocations.map { it.getLatLng() })
val placeIdentifier = routeTrackingState.getPlaceIdentifier()
val activityType = routeTrackingState.getActivityType()
val activityData = ActivityDataModel(
activityId,
activityType,
activityName,
routeImage = "", // local storage does not include
placeIdentifier,
startTime ?: endTime - duration,
endTime,
duration,
distance,
encodedPolyline,
AthleteInfo(userId = userId) // local storage does not include
)
return when (activityType) {
ActivityType.Running -> {
val pace =
UnitConverter.TimeMinute.fromRawValue(duration) /
UnitConverter.DistanceKm.fromRawValue(distance)
RunningActivityModel(activityData, pace, cadence = 0)
}
ActivityType.Cycling -> {
val speed =
UnitConverter.DistanceKm.fromRawValue(distance) /
UnitConverter.TimeHour.fromRawValue(duration)
CyclingActivityModel(activityData, speed)
}
else -> throw UnsupportedOperationException(
"Saving unknown activity type $activityType"
)
}
}
}
| 0 |
Kotlin
|
3
| 7 |
31cc16d0fb37816db4dc434c925360624e38e35c
| 4,659 |
myrun
|
MIT License
|
voyager-tab-navigator/src/commonMain/kotlin/cafe/adriel/voyager/navigator/tab/TabNavigator.kt
|
adrielcafe
| 387,613,592 | false | null |
package cafe.adriel.voyager.navigator.tab
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import cafe.adriel.voyager.navigator.Navigator
import cafe.adriel.voyager.navigator.NavigatorDisposeBehavior
public typealias TabNavigatorContent = @Composable (tabNavigator: TabNavigator) -> Unit
public val LocalTabNavigator: ProvidableCompositionLocal<TabNavigator> =
staticCompositionLocalOf { error("TabNavigator not initialized") }
@Composable
public fun TabNavigator(
tab: Tab,
disposeNestedNavigators: Boolean = false,
content: TabNavigatorContent = { CurrentTab() }
) {
Navigator(
screen = tab,
disposeBehavior = NavigatorDisposeBehavior(
disposeNestedNavigators = disposeNestedNavigators,
disposeSteps = false
),
onBackPressed = null
) { navigator ->
val tabNavigator = remember(navigator) {
TabNavigator(navigator)
}
CompositionLocalProvider(LocalTabNavigator provides tabNavigator) {
content(tabNavigator)
}
}
}
public class TabNavigator internal constructor(
private val navigator: Navigator
) {
public var current: Tab
get() = navigator.lastItem as Tab
set(tab) = navigator.replaceAll(tab)
@Composable
public fun saveableState(
key: String,
tab: Tab = current,
content: @Composable () -> Unit
) {
navigator.saveableState(key, tab, content = content)
}
}
| 31 | null |
39
| 945 |
d7932b28cf8c2545fcd52c3883467a648f9d2888
| 1,686 |
voyager
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/sagemaker/CfnModelPropsDsl.kt
|
cloudshiftinc
| 667,063,030 | false | null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.sagemaker
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.dsl.CfnTagDsl
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.sagemaker.CfnModel
import software.amazon.awscdk.services.sagemaker.CfnModelProps
/**
* Properties for defining a `CfnModel`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.sagemaker.*;
* Object environment;
* CfnModelProps cfnModelProps = CfnModelProps.builder()
* .executionRoleArn("executionRoleArn")
* // the properties below are optional
* .containers(List.of(ContainerDefinitionProperty.builder()
* .containerHostname("containerHostname")
* .environment(environment)
* .image("image")
* .imageConfig(ImageConfigProperty.builder()
* .repositoryAccessMode("repositoryAccessMode")
* // the properties below are optional
* .repositoryAuthConfig(RepositoryAuthConfigProperty.builder()
* .repositoryCredentialsProviderArn("repositoryCredentialsProviderArn")
* .build())
* .build())
* .inferenceSpecificationName("inferenceSpecificationName")
* .mode("mode")
* .modelDataUrl("modelDataUrl")
* .modelPackageName("modelPackageName")
* .multiModelConfig(MultiModelConfigProperty.builder()
* .modelCacheSetting("modelCacheSetting")
* .build())
* .build()))
* .enableNetworkIsolation(false)
* .inferenceExecutionConfig(InferenceExecutionConfigProperty.builder()
* .mode("mode")
* .build())
* .modelName("modelName")
* .primaryContainer(ContainerDefinitionProperty.builder()
* .containerHostname("containerHostname")
* .environment(environment)
* .image("image")
* .imageConfig(ImageConfigProperty.builder()
* .repositoryAccessMode("repositoryAccessMode")
* // the properties below are optional
* .repositoryAuthConfig(RepositoryAuthConfigProperty.builder()
* .repositoryCredentialsProviderArn("repositoryCredentialsProviderArn")
* .build())
* .build())
* .inferenceSpecificationName("inferenceSpecificationName")
* .mode("mode")
* .modelDataUrl("modelDataUrl")
* .modelPackageName("modelPackageName")
* .multiModelConfig(MultiModelConfigProperty.builder()
* .modelCacheSetting("modelCacheSetting")
* .build())
* .build())
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .vpcConfig(VpcConfigProperty.builder()
* .securityGroupIds(List.of("securityGroupIds"))
* .subnets(List.of("subnets"))
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-model.html)
*/
@CdkDslMarker
public class CfnModelPropsDsl {
private val cdkBuilder: CfnModelProps.Builder = CfnModelProps.builder()
private val _containers: MutableList<Any> = mutableListOf()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* @param containers Specifies the containers in the inference pipeline.
*/
public fun containers(vararg containers: Any) {
_containers.addAll(listOf(*containers))
}
/**
* @param containers Specifies the containers in the inference pipeline.
*/
public fun containers(containers: Collection<Any>) {
_containers.addAll(containers)
}
/**
* @param containers Specifies the containers in the inference pipeline.
*/
public fun containers(containers: IResolvable) {
cdkBuilder.containers(containers)
}
/**
* @param enableNetworkIsolation Isolates the model container.
* No inbound or outbound network calls can be made to or from the model container.
*/
public fun enableNetworkIsolation(enableNetworkIsolation: Boolean) {
cdkBuilder.enableNetworkIsolation(enableNetworkIsolation)
}
/**
* @param enableNetworkIsolation Isolates the model container.
* No inbound or outbound network calls can be made to or from the model container.
*/
public fun enableNetworkIsolation(enableNetworkIsolation: IResolvable) {
cdkBuilder.enableNetworkIsolation(enableNetworkIsolation)
}
/**
* @param executionRoleArn The Amazon Resource Name (ARN) of the IAM role that SageMaker can
* assume to access model artifacts and docker image for deployment on ML compute instances or for
* batch transform jobs.
* Deploying on ML compute instances is part of model hosting. For more information, see
* [SageMaker Roles](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) .
*
*
* To be able to pass this role to SageMaker, the caller of this API must have the `iam:PassRole`
* permission.
*/
public fun executionRoleArn(executionRoleArn: String) {
cdkBuilder.executionRoleArn(executionRoleArn)
}
/**
* @param inferenceExecutionConfig Specifies details of how containers in a multi-container
* endpoint are called.
*/
public fun inferenceExecutionConfig(inferenceExecutionConfig: IResolvable) {
cdkBuilder.inferenceExecutionConfig(inferenceExecutionConfig)
}
/**
* @param inferenceExecutionConfig Specifies details of how containers in a multi-container
* endpoint are called.
*/
public
fun inferenceExecutionConfig(inferenceExecutionConfig: CfnModel.InferenceExecutionConfigProperty) {
cdkBuilder.inferenceExecutionConfig(inferenceExecutionConfig)
}
/**
* @param modelName The name of the new model.
*/
public fun modelName(modelName: String) {
cdkBuilder.modelName(modelName)
}
/**
* @param primaryContainer The location of the primary docker image containing inference code,
* associated artifacts, and custom environment map that the inference code uses when the model is
* deployed for predictions.
*/
public fun primaryContainer(primaryContainer: IResolvable) {
cdkBuilder.primaryContainer(primaryContainer)
}
/**
* @param primaryContainer The location of the primary docker image containing inference code,
* associated artifacts, and custom environment map that the inference code uses when the model is
* deployed for predictions.
*/
public fun primaryContainer(primaryContainer: CfnModel.ContainerDefinitionProperty) {
cdkBuilder.primaryContainer(primaryContainer)
}
/**
* @param tags A list of key-value pairs to apply to this resource.
* For more information, see [Resource
* Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* and [Using Cost Allocation
* Tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what)
* in the *AWS Billing and Cost Management User Guide* .
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* @param tags A list of key-value pairs to apply to this resource.
* For more information, see [Resource
* Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* and [Using Cost Allocation
* Tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what)
* in the *AWS Billing and Cost Management User Guide* .
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
/**
* @param vpcConfig A
* [VpcConfig](https://docs.aws.amazon.com/sagemaker/latest/dg/API_VpcConfig.html) object that
* specifies the VPC that you want your model to connect to. Control access to and from your model
* container by configuring the VPC. `VpcConfig` is used in hosting services and in batch transform.
* For more information, see [Protect Endpoints by Using an Amazon Virtual Private
* Cloud](https://docs.aws.amazon.com/sagemaker/latest/dg/host-vpc.html) and [Protect Data in Batch
* Transform Jobs by Using an Amazon Virtual Private
* Cloud](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-vpc.html) .
*/
public fun vpcConfig(vpcConfig: IResolvable) {
cdkBuilder.vpcConfig(vpcConfig)
}
/**
* @param vpcConfig A
* [VpcConfig](https://docs.aws.amazon.com/sagemaker/latest/dg/API_VpcConfig.html) object that
* specifies the VPC that you want your model to connect to. Control access to and from your model
* container by configuring the VPC. `VpcConfig` is used in hosting services and in batch transform.
* For more information, see [Protect Endpoints by Using an Amazon Virtual Private
* Cloud](https://docs.aws.amazon.com/sagemaker/latest/dg/host-vpc.html) and [Protect Data in Batch
* Transform Jobs by Using an Amazon Virtual Private
* Cloud](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-vpc.html) .
*/
public fun vpcConfig(vpcConfig: CfnModel.VpcConfigProperty) {
cdkBuilder.vpcConfig(vpcConfig)
}
public fun build(): CfnModelProps {
if(_containers.isNotEmpty()) cdkBuilder.containers(_containers)
if(_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 1 |
Kotlin
|
0
| 0 |
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 9,344 |
awscdk-dsl-kotlin
|
Apache License 2.0
|
better-dating-backend/src/main/kotlin/ua/betterdating/backend/handlers/PlaceHandler.kt
|
skivol
| 198,444,119 | false |
{"TypeScript": 340550, "Kotlin": 260110, "Shell": 20344, "CSS": 6335, "JavaScript": 5964, "PLpgSQL": 5214, "Dockerfile": 3426, "HTML": 2170, "Vim Script": 440}
|
package ua.betterdating.backend.handlers
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.transaction.reactive.TransactionalOperator
import org.springframework.transaction.reactive.executeAndAwait
import org.springframework.web.reactive.function.server.*
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.server.ServerWebInputException
import ua.betterdating.backend.*
import ua.betterdating.backend.data.*
import ua.betterdating.backend.external.GoogleTimeZoneApi
import ua.betterdating.backend.external.MapboxApi
import ua.betterdating.backend.external.MapboxConfig
import ua.betterdating.backend.tasks.findAvailableDatingSpotsIn
import ua.betterdating.backend.tasks.generateAndSaveDateVerificationToken
import ua.betterdating.backend.utils.*
import java.util.*
open class LatLng(
val lat: Double,
val lng: Double,
)
class Coordinates(
lat: Double,
lng: Double,
val specific: Boolean
) : LatLng(lat, lng)
class PlaceHandler(
private val mapboxApi: MapboxApi,
private val googleTimeZoneApi: GoogleTimeZoneApi,
private val pairsRepository: PairsRepository,
private val placeRepository: PlaceRepository,
private val datesRepository: DatesRepository,
private val emailRepository: EmailRepository,
private val loginInformationRepository: LoginInformationRepository,
private val expiringTokenRepository: ExpiringTokenRepository,
private val dateVerificationTokenDataRepository: DateVerificationTokenDataRepository,
private val historyRepository: HistoryRepository,
private val passwordEncoder: PasswordEncoder,
private val transactionalOperator: TransactionalOperator,
private val mailSender: FreemarkerMailSender,
private val mapboxConfig: MapboxConfig,
) {
private val log by LoggerDelegate()
suspend fun resolvePopulatedLocalityCoordinatesForDate(request: ServerRequest): ServerResponse {
val dateId = ensureCan(
PlaceAction.AddPlace, request, dateIdFromRequest(request)
).dateInfo.id
// 1. resolve place from pair
val populatedLocality =
pairsRepository.findPairByDate(dateId).firstProfileSnapshot!!.populatedLocality
// use mapbox geocoding for initial positioning
val coordinates = mapboxApi.forwardGeocoding("${populatedLocality.name} ${populatedLocality.region}") ?: {
// or center of Ukraine/Russia/Belarus/Kazakhstan (or appropriate country in general) if couldn't find specific place coordinates
val latLng = when (populatedLocality.country) {
"Россия" -> arrayOf(55.633315, 37.796245)
"Республика Беларусь" -> arrayOf(53.90175546268201, 27.55594010756711)
"Республика Казахстан" -> arrayOf(48.154584222766196, 67.2716195873904)
// Украина
else -> arrayOf(49.47954694610455, 31.482421606779102)
}
Coordinates(latLng[0], latLng[1], false)
}
log.debug("Resolved {} coordinates", coordinates)
return ok().json().bodyValueAndAwait(coordinates)
}
@Suppress("UNUSED_PARAMETER")
suspend fun token(request: ServerRequest) = ok().json().bodyValueAndAwait(object {
val token = mapboxConfig.publicAccessToken
})
private fun dateIdFromRequest(request: ServerRequest) =
UUID.fromString(
request.queryParam("dateId").orElseThrow { ServerWebInputException("no dateId parameter specified") })
private data class PlaceHandlerContext(val dateInfo: DateInfo, val datingPair: DatingPair, val relevantPlaces: List<Place>, val currentUserId: UUID)
private suspend fun ensureCan(
placeAction: PlaceAction,
request: ServerRequest,
dateId: UUID
): PlaceHandlerContext {
val dateAndPair = resolveDateAndPair(datesRepository, pairsRepository, dateId)
val (relevantDate, relevantPair) = dateAndPair
val userId = UUID.fromString(request.awaitPrincipal()!!.name)
val relevantDatingPlaces = if (relevantDate.placeId != null) placeRepository.allById(relevantDate.placeId) else emptyList()
val error = when (placeAction) {
PlaceAction.AddPlace -> {
val mostRecentPlaceSuggestedByCurrentUser = { relevantDatingPlaces.maxByOrNull { it.createdAt }?.let { it.suggestedBy == userId } ?: false }
when {
!setOf(DateStatus.WaitingForPlace, DateStatus.WaitingForPlaceApproval).contains(relevantDate.status) -> "date does not need new place to be added"
(relevantDatingPlaces.isEmpty() && userId != relevantPair.firstProfileId) || mostRecentPlaceSuggestedByCurrentUser() -> "other user should be adding place suggestion"
else -> null
}
}
PlaceAction.VerifyPlace -> {
val placeSuggestedByOtherUser = relevantDatingPlaces.firstOrNull { it.suggestedBy != userId }
when {
relevantDate.status != DateStatus.WaitingForPlaceApproval -> "date does not need new place to be approved"
placeSuggestedByOtherUser == null -> "no place suggested by other user that can be checked"
else -> null
}
}
PlaceAction.ViewPlace -> {
if (!setOf(DateStatus.Scheduled, DateStatus.Rescheduled, DateStatus.PartialCheckIn).contains(relevantDate.status)) "date is not currently scheduled or in partial check-in state"
else null
}
}
if (error != null) throw ServerWebInputException(error)
return PlaceHandlerContext(relevantDate, relevantPair, relevantDatingPlaces, userId)
}
private class AddPlaceRequest(
val dateId: UUID,
val name: String,
lat: Double,
lng: Double,
) : LatLng(lat, lng)
suspend fun addPlace(request: ServerRequest): ServerResponse {
val addPlaceRequest = request.awaitBody<AddPlaceRequest>()
val (dateInfo, pair, relevantPlaces, currentUserId) = ensureCan(PlaceAction.AddPlace, request, addPlaceRequest.dateId)
val dateId = dateInfo.id
val populatedLocality = pair.firstProfileSnapshot!!.populatedLocality
val firstRelevantPlace = relevantPlaces.firstOrNull()
// "version" selection logic covers more than is allowed currently
// to avoid accidentally updating the place suggested by other user at all costs
val version = when (relevantPlaces.size) {
0 -> 1
1 -> when {
firstRelevantPlace!!.suggestedBy == currentUserId -> firstRelevantPlace.version
firstRelevantPlace.version == 1 -> 2
else -> 1
}
// 2 unsettled places
else -> relevantPlaces.first { it.suggestedBy == currentUserId }.version
}
val place = Place(
id = firstRelevantPlace?.id ?: UUID.randomUUID(),
name = addPlaceRequest.name,
latitude = addPlaceRequest.lat,
longitude = addPlaceRequest.lng,
populatedLocalityId = populatedLocality.id,
suggestedBy = currentUserId,
status = PlaceStatus.WaitingForApproval,
version = version
)
// perform reverse geocoding to verify if selected point is within current populated locality
val withinLocality = mapboxApi.pointWithinPopulatedLocality(addPlaceRequest.lat, addPlaceRequest.lng, populatedLocality)
if (withinLocality == false) {
throw NotInTargetPopulatedLocalityException(populatedLocality.name)
}
val suggestOtherPlaceFlow = relevantPlaces.isNotEmpty()
val subject = "Нужно проверить ${if (suggestOtherPlaceFlow) "новое " else ""}место предложенное для организации свидания"
val otherUserId = if (pair.firstProfileId == currentUserId) pair.secondProfileId else pair.firstProfileId
val otherUserProfileEmail = emailRepository.findById(otherUserId)!!.email
val otherUserProfileLastHost = loginInformationRepository.find(otherUserId).lastHost
trackingTooCloseToOtherPlacesException(currentUserId) {
transactionalOperator.executeAndAwait {
// save while checking new point is not too close to existing other points
val upsertCount = placeRepository.upsert(place, distance)
if (upsertCount == 0) {
checkTooClosePoints(place, distance)
}
datesRepository.upsert(
dateInfo.copy(
status = DateStatus.WaitingForPlaceApproval,
placeId = place.id,
)
)
// send mail to the second user
mailSender.sendLink(
"HelpToChooseThePlace.ftlh",
otherUserProfileEmail,
subject,
otherUserProfileLastHost,
"проверка-места?свидание=${dateId}",
) { link ->
object {
val title = subject
val actionLabel = "Посмотреть место встречи"
val actionUrl = link
}
}
}
}
return okEmptyJsonObject()
}
private class ApprovePlaceRequest(val dateId: UUID)
suspend fun approvePlace(request: ServerRequest): ServerResponse {
val approvePlaceRequest = request.awaitBody<ApprovePlaceRequest>()
val (dateInfo, pair, relevantPlaces, currentUserId) = ensureCan(PlaceAction.VerifyPlace, request, approvePlaceRequest.dateId)
val placeToApprove = relevantPlaces.firstOrNull { it.suggestedBy != currentUserId } ?: throw badRequestException("no place to be approved by current user was found")
trackingTooCloseToOtherPlacesException(currentUserId) {
transactionalOperator.executeAndAwait {
if (relevantPlaces.size > 1) { // we're having several place suggestions for one date (that is, in "suggest other place" flow)
// delete all, because we might be changing the version of approved place to "1" in the upsert below in this case
// and we don't want the old version to hang around
placeRepository.deleteAllById(placeToApprove.id)
}
val finalPlace =
placeToApprove.copy(status = PlaceStatus.Approved, approvedBy = currentUserId, version = 1)
val upsertCount = placeRepository.upsert(finalPlace, distance)
if (upsertCount == 0) {
checkTooClosePoints(placeToApprove, distance)
}
val spots = findAvailableDatingSpotsIn(
datesRepository,
googleTimeZoneApi,
pair.firstProfileSnapshot!!.populatedLocality
)
val whenAndWhere = spots.shuffled().first { it.place.id == dateInfo.placeId }
datesRepository.upsert(
dateInfo.copy(
whenScheduled = whenAndWhere.timeAndDate,
status = DateStatus.Scheduled,
placeId = finalPlace.id,
placeVersion = finalPlace.version,
)
)
// notify users about scheduled date
val firstProfileEmail = emailRepository.findById(pair.firstProfileId)!!.email
val firstProfileLastHost = loginInformationRepository.find(pair.firstProfileId).lastHost
val body =
"$automaticDateAndTime $striveToComeToTheDate $beResponsibleAndAttentive $additionalInfoCanBeFoundOnSite"
val secondProfile = emailRepository.findById(pair.secondProfileId)!!
val dateVerificationToken =
generateAndSaveDateVerificationToken(
secondProfile.id,
whenAndWhere.timeAndDate,
dateInfo.id,
passwordEncoder,
expiringTokenRepository,
dateVerificationTokenDataRepository
)
mailSender.dateOrganizedMessage(
firstProfileEmail,
whenAndWhere,
bodyWithVerificationToken(body, dateVerificationToken),
firstProfileLastHost
)
val secondProfileLastHost = loginInformationRepository.find(pair.secondProfileId).lastHost
mailSender.dateOrganizedMessage(
secondProfile.email,
whenAndWhere,
bodyMentioningVerificationToken(body),
secondProfileLastHost
)
}
}
return okEmptyJsonObject()
}
private enum class PlaceAction {
AddPlace, VerifyPlace, ViewPlace
}
suspend fun getPlaceData(request: ServerRequest): ServerResponse {
val action = when (
request.queryParam("action").orElseThrow { ServerWebInputException("'action' query parameter is missing") }
) {
"check" -> PlaceAction.VerifyPlace
"view" -> PlaceAction.ViewPlace
else -> throw ServerWebInputException("'action' query param expected values are 'check'/'view'")
}
val (date, _, places, currentUserId) = ensureCan(action, request, dateIdFromRequest(request))
if (places.isEmpty()) throw ServerWebInputException("No place connected to the date")
val result = when (action) {
PlaceAction.VerifyPlace -> places.first { it.suggestedBy != currentUserId }
// ViewPlace
else -> places.first { it.version == date.placeVersion }
}
return ok().json().bodyValueAndAwait(result)
}
private suspend fun trackingTooCloseToOtherPlacesException(currentUserId: UUID, transaction: suspend () -> Unit) {
try {
transaction.invoke()
} catch (e: TooCloseToOtherPlacesException) {
historyRepository.trackTooCloseToOtherPlacesException(currentUserId, e)
throw e
}
}
private suspend fun checkTooClosePoints(place: Place, distance: Double) {
val tooClosePoints =
placeRepository.fetchTooClosePlaces(place.populatedLocalityId, place.longitude, place.latitude, distance)
throw TooCloseToOtherPlacesException(tooClosePoints, distance)
}
}
suspend fun resolveDateAndPair(datesRepository: DatesRepository, pairsRepository: PairsRepository, dateId: UUID): Pair<DateInfo, DatingPair> {
val relevantDate =
datesRepository.findById(dateId) ?: throw ServerWebInputException("no date with provided id was found")
val relevantPair = pairsRepository.findPairByDate(dateId)
return Pair(relevantDate, relevantPair)
}
| 1 |
TypeScript
|
0
| 1 |
d60eac61721ff0b8b2a4075a3c744793d3dd098a
| 15,163 |
better-dating
|
Apache License 2.0
|
base/src/main/java/de/whitefrog/frogr/repository/DefaultModelRepository.kt
|
joewhite86
| 118,778,368 | false | null |
package de.whitefrog.frogr.repository
import de.whitefrog.frogr.model.BaseModel
import de.whitefrog.frogr.model.Model
/**
* Will be used by [RepositoryFactory] method when no other repository was found.
*/
class DefaultModelRepository<T : Model>(modelName: String) : BaseModelRepository<T>(modelName) {
override fun getModelClass(): Class<*> {
if (modelClass == null) {
modelClass = cache().getModel(type)
if (modelClass == null) modelClass = BaseModel::class.java
}
return modelClass
}
}
| 1 |
Kotlin
|
1
| 2 |
396ac4243acb7b75f624431e61d691e3fb6c9103
| 522 |
frogr
|
MIT License
|
prime-router/src/test/kotlin/fhirengine/azure/FhirFunctionIntegrationTests.kt
|
CDCgov
| 304,423,150 | false |
{"Kotlin": 4641633, "CSS": 3370586, "TypeScript": 1490450, "Java": 916549, "HCL": 282617, "MDX": 146323, "PLpgSQL": 77695, "HTML": 69589, "Shell": 66846, "SCSS": 64177, "Smarty": 51325, "RouterOS Script": 17080, "Python": 13706, "Makefile": 8166, "JavaScript": 8115, "Dockerfile": 2304}
|
package fhirengine.azure
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import gov.cdc.prime.router.ActionLogger
import gov.cdc.prime.router.ClientSource
import gov.cdc.prime.router.CustomerStatus
import gov.cdc.prime.router.DeepOrganization
import gov.cdc.prime.router.FileSettings
import gov.cdc.prime.router.Metadata
import gov.cdc.prime.router.Options
import gov.cdc.prime.router.Organization
import gov.cdc.prime.router.Receiver
import gov.cdc.prime.router.Report
import gov.cdc.prime.router.SettingsProvider
import gov.cdc.prime.router.Topic
import gov.cdc.prime.router.azure.ActionHistory
import gov.cdc.prime.router.azure.BlobAccess
import gov.cdc.prime.router.azure.DatabaseAccess
import gov.cdc.prime.router.azure.Event
import gov.cdc.prime.router.azure.ProcessEvent
import gov.cdc.prime.router.azure.QueueAccess
import gov.cdc.prime.router.azure.WorkflowEngine
import gov.cdc.prime.router.azure.db.enums.TaskAction
import gov.cdc.prime.router.azure.db.tables.ActionLog
import gov.cdc.prime.router.azure.db.tables.Task
import gov.cdc.prime.router.azure.db.tables.pojos.Action
import gov.cdc.prime.router.azure.db.tables.pojos.ReportFile
import gov.cdc.prime.router.azure.db.tables.pojos.ReportLineage
import gov.cdc.prime.router.cli.tests.CompareData
import gov.cdc.prime.router.common.TestcontainersUtils
import gov.cdc.prime.router.db.ReportStreamTestDatabaseContainer
import gov.cdc.prime.router.db.ReportStreamTestDatabaseSetupExtension
import gov.cdc.prime.router.fhirengine.azure.FHIRFunctions
import gov.cdc.prime.router.fhirengine.engine.FHIRConverter
import gov.cdc.prime.router.fhirengine.engine.FHIRRouter
import gov.cdc.prime.router.fhirengine.engine.FHIRTranslator
import gov.cdc.prime.router.fhirengine.engine.QueueMessage
import gov.cdc.prime.router.fhirengine.engine.elrRoutingQueueName
import gov.cdc.prime.router.fhirengine.engine.elrTranslationQueueName
import gov.cdc.prime.router.history.db.ReportGraph
import gov.cdc.prime.router.metadata.LookupTable
import gov.cdc.prime.router.report.ReportService
import gov.cdc.prime.router.unittest.UnitTestUtils
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.spyk
import io.mockk.verify
import org.jooq.impl.DSL
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import java.io.File
import java.time.OffsetDateTime
import java.util.UUID
private const val MULTIPLE_TARGETS_FHIR_PATH = "src/test/resources/fhirengine/engine/valid_data_multiple_targets.fhir"
private const val VALID_FHIR_PATH = "src/test/resources/fhirengine/engine/valid_data.fhir"
private const val hl7_record =
"MSH|^~\\&|CDC PRIME - Atlanta,^2.16.840.1.114222.4.1.237821^ISO|Winchester House^05D2222542^" +
"ISO|CDPH FL REDIE^2.16.840.1.114222.4.3.3.10.1.1^ISO|CDPH_CID^2.16.840.1.114222.4.1.214104^ISO|202108031315" +
"11.0147+0000||ORU^R01^ORU_R01|1234d1d1-95fe-462c-8ac6-46728dba581c|P|2.5.1|||NE|NE|USA|UNICODE UTF-8|||PHLab" +
"Report-NoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO\n" +
"SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME Data Hub|0.1-SNAPSHOT||20210726\n" +
"PID|1||09d12345-0987-1234-1234-111b1ee0879f^^^Winchester House&05D2222542&ISO^PI^&05D2222542&ISO||Bunny^Bug" +
"s^C^^^^L||19000101|M||2106-3^White^HL70005^^^^2.5.1|12345 Main St^^San Jose^FL^95125^USA^^^06085||(123)456-" +
"7890^PRN^PH^^1^123^4567890|||||||||N^Non Hispanic or Latino^HL70189^^^^2.9||||||||N\n" +
"ORC|RE|1234d1d1-95fe-462c-8ac6-46728dba581c^Winchester House^05D2222542^ISO|1234d1d1-95fe-462c-8ac6-46728db" +
"a581c^Winchester House^05D2222542^ISO|||||||||1679892871^Doolittle^Doctor^^^^^^CMS&2.16.840.1.113883.3.249&" +
"ISO^^^^NPI||(123)456-7890^WPN^PH^^1^123^4567890|20210802||||||Winchester House|6789 Main St^^San Jose^FL^95" +
"126^^^^06085|(123)456-7890^WPN^PH^^1^123^4567890|6789 Main St^^San Jose^FL^95126\n" +
"OBR|1|1234d1d1-95fe-462c-8ac6-46728dba581c^Winchester House^05D2222542^ISO|1234d1d1-95fe-462c-8ac6-46728dba" +
"581c^Winchester House^05D2222542^ISO|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by" +
" Rapid immunoassay^LN^^^^2.68|||202108020000-0500|202108020000-0500||||||||1679892871^Doolittle^Doctor^^^^" +
"^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|(123)456-7890^WPN^PH^^1^123^4567890|||||202108020000-0500|||F\n" +
"OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN^^^^2." +
"68||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078^^^^2.7|||F|||20210802000" +
"0-0500|05D2222542^ISO||10811877011290_DIT^10811877011290^99ELR^^^^2.68^^10811877011290_DIT||20" +
"2108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D2222542|6789 Main St^^" +
"San Jose^FL^95126^^^^06085\n" +
"OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||N^No^HL70136||||||F|||202" +
"108020000-0500|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX" +
"^^^05D2222542|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202108020000-0500" +
"|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D2222542|" +
"6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202108020000-05" +
"00|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D22225" +
"42|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||2021080" +
"20000-0500|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^" +
"05D2222542|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"SPM|1|1234d1d1-95fe-462c-8ac6-46728dba581c&&05D2222542&ISO^1234d1d1-95fe-462c-8ac6-46728dba581c&&05D22225" +
"42&ISO||445297001^Swab of internal nose^SCT^^^^2.67||||53342003^Internal nose structure (body structure)^" +
"SCT^^^^2020-09-01|||||||||202108020000-0500|20210802000006.0000-0500"
@Suppress("ktlint:standard:max-line-length")
private const val fhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}"""
@Suppress("ktlint:standard:max-line-length")
private const val codelessFhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}"""
@Suppress("ktlint:standard:max-line-length")
private const val bulkFhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}
{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c09876","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dbau8cd"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}
{}
{"resourceType":"Bund}"""
@Suppress("ktlint:standard:max-line-length")
private const val cleanHL7Record =
"""MSH|^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Suppress("ktlint:standard:max-line-length")
private const val cleanHL7RecordConverted =
"""{"resourceType":"Bundle","id":"1712756879851727000.c7991c94-bacb-4339-9574-6cdd2070cdc1","meta":{"lastUpdated":"2024-04-10T09:47:59.857-04:00"},"identifier":{"system":"https://reportstream.cdc.gov/prime-router","value":"371784"},"type":"message","timestamp":"2021-02-10T17:07:37.000-05:00","entry":[{"fullUrl":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e","resource":{"resourceType":"MessageHeader","id":"4aeed951-99a9-3152-8885-6b0acc6dd35e","meta":{"tag":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0103","code":"P"}]},"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/msh-message-header","extension":[{"url":"MSH.7","valueString":"20210210170737"},{"url":"MSH.15","valueString":"NE"},{"url":"MSH.16","valueString":"NE"},{"url":"MSH.21","valueIdentifier":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"ELR_Receiver"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.9.11"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"PHLabReportNoAck"}}]}],"eventCoding":{"system":"http://terminology.hl7.org/CodeSystem/v2-0003","code":"R01","display":"ORU^R01^ORU_R01"},"destination":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.5"}],"name":"PRIME_DOH","_endpoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"receiver":{"reference":"Organization/1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9"}}],"sender":{"reference":"Organization/1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1"},"source":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CDC PRIME - Atlanta, Georgia (Dekalb)"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.114222.4.1.237821"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueString":"ISO"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.3"}],"software":"PRIME ReportStream","version":"0.1-SNAPSHOT","endpoint":"urn:oid:2.16.840.1.114222.4.1.237821"}}},{"fullUrl":"Organization/1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1","resource":{"resourceType":"Organization","id":"1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}],"address":[{"country":"USA"}]}},{"fullUrl":"Organization/1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9","resource":{"resourceType":"Organization","id":"1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.6"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Prime ReportStream"}]}},{"fullUrl":"Provenance/1712756880222129000.288337a9-f487-4208-94a3-7c93996d1161","resource":{"resourceType":"Provenance","id":"1712756880222129000.288337a9-f487-4208-94a3-7c93996d1161","target":[{"reference":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e"},{"reference":"DiagnosticReport/1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181"}],"recorded":"2021-02-10T17:07:37Z","activity":{"coding":[{"display":"ORU^R01^ORU_R01"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"author"}]},"who":{"reference":"Organization/1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3"}}],"entity":[{"role":"source","what":{"reference":"Device/1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d"}}]}},{"fullUrl":"Organization/1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3","resource":{"resourceType":"Organization","id":"1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}]}},{"fullUrl":"Organization/1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c","resource":{"resourceType":"Organization","id":"1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c","name":"Centers for Disease Control and Prevention"}},{"fullUrl":"Device/1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d","resource":{"resourceType":"Device","id":"1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-vendor-org","valueReference":{"reference":"Organization/1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c"}}],"manufacturer":"Centers for Disease Control and Prevention","deviceName":[{"name":"PRIME ReportStream","type":"manufacturer-name"}],"modelNumber":"0.1-SNAPSHOT","version":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-install-date","valueDateTime":"2021-02-10","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"20210210"}]}}],"value":"0.1-SNAPSHOT"}]}},{"fullUrl":"Provenance/1712756880233764000.4cf51f91-0e13-467e-8861-1e4ad2899343","resource":{"resourceType":"Provenance","id":"1712756880233764000.4cf51f91-0e13-467e-8861-1e4ad2899343","recorded":"2024-04-10T09:48:00Z","policy":["http://hl7.org/fhir/uv/v2mappings/message-oru-r01-to-bundle"],"activity":{"coding":[{"code":"v2-FHIR transformation"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"assembler"}]},"who":{"reference":"Organization/1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f"}}]}},{"fullUrl":"Organization/1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f","resource":{"resourceType":"Organization","id":"1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f","identifier":[{"value":"CDC PRIME - Atlanta"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301"}]},"system":"urn:ietf:rfc:3986","value":"2.16.840.1.114222.4.1.237821"}]}},{"fullUrl":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9","resource":{"resourceType":"Patient","id":"1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/pid-patient","extension":[{"url":"PID.8","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"}],"code":"F"}]}},{"url":"PID.30","valueString":"N"}]},{"url":"http://ibm.com/fhir/cdm/StructureDefinition/local-race-cd","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70005"}],"system":"http://terminology.hl7.org/CodeSystem/v3-Race","version":"2.5.1","code":"2106-3","display":"White"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/ethnic-group","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70189"}],"system":"http://terminology.hl7.org/CodeSystem/v2-0189","code":"U","display":"Unknown"}]}}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cx-identifier","extension":[{"url":"CX.5","valueString":"PI"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"PID.3"}],"type":{"coding":[{"code":"PI"}]},"value":"2a14112c-ece1-4f82-915c-7b3a8d152eda","assigner":{"reference":"Organization/1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca"}}],"name":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xpn-human-name","extension":[{"url":"XPN.2","valueString":"Kareem"},{"url":"XPN.3","valueString":"Millie"},{"url":"XPN.7","valueString":"L"}]}],"use":"official","family":"Buckridge","given":["Kareem","Millie"]}],"telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"211"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"2240784"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.1","valueString":"7275555555:1:"},{"url":"XTN.2","valueString":"PRN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"2240784"}]}],"system":"email","use":"home"}],"gender":"female","birthDate":"1958-08-10","_birthDate":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"19580810"}]},"deceasedBoolean":false,"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"688 Leighann Inlet"}]}]}],"line":["688 Leighann Inlet"],"city":"South Rodneychester","district":"48077","state":"TX","postalCode":"67071"}]}},{"fullUrl":"Organization/1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca","resource":{"resourceType":"Organization","id":"1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"}]}},{"fullUrl":"Provenance/1712756880258584000.921c8787-5833-457c-a27f-b335a02cb038","resource":{"resourceType":"Provenance","id":"1712756880258584000.921c8787-5833-457c-a27f-b335a02cb038","target":[{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"}],"recorded":"2024-04-10T09:48:00Z","activity":{"coding":[{"system":"https://terminology.hl7.org/CodeSystem/v3-DataOperation","code":"UPDATE"}]}}},{"fullUrl":"Observation/1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e","resource":{"resourceType":"Observation","id":"1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/analysis-date-time","valueDateTime":"2021-02-09T00:00:00-06:00","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"},{"url":"OBX.17","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"performer":[{"reference":"Organization/1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43"}],"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"260415000","display":"Not detected"}]},"interpretation":[{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70078"}],"code":"N","display":"Normal (applies to non-numeric results)"}]}],"method":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}},{"fullUrl":"Organization/1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43","resource":{"resourceType":"Organization","id":"1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xon-organization","extension":[{"url":"XON.10","valueString":"10D0876999"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBX.25"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CLIA"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.4.7"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"10D0876999"}],"name":"Avante at Ormond Beach","address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"Observation/1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c","resource":{"resourceType":"Observation","id":"1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95418-0","display":"Whether patient is employed in a healthcare setting"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa","resource":{"resourceType":"Observation","id":"1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95417-2","display":"First test for condition of interest"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e","resource":{"resourceType":"Observation","id":"1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95421-4","display":"Resides in a congregate care setting"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Observation/1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f","resource":{"resourceType":"Observation","id":"1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95419-8","display":"Has symptoms related to condition of interest"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Specimen/1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce","resource":{"resourceType":"Specimen","id":"1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"OBR"}]}},{"fullUrl":"Specimen/1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a","resource":{"resourceType":"Specimen","id":"1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"SPM"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Component","valueString":"SPM.2.1"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PGN"}]},"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}],"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"258500001","display":"Nasopharyngeal swab"}]},"receivedTime":"2021-02-09T00:00:00-06:00","_receivedTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"collection":{"collectedDateTime":"2021-02-09T00:00:00-06:00","_collectedDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"bodySite":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","version":"2020-09-01","code":"71836000","display":"Nasopharyngeal structure (body structure)"}]}}}},{"fullUrl":"ServiceRequest/1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e","resource":{"resourceType":"ServiceRequest","id":"1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/business-event","valueCode":"RE"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/orc-common-order","extension":[{"url":"orc-21-ordering-facility-name","valueReference":{"reference":"Organization/1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2"}},{"url":"orc-22-ordering-facility-address","valueAddress":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}},{"url":"orc-24-ordering-provider-address","valueAddress":{"postalCode":"32174"}},{"url":"orc-12-ordering-provider","valueReference":{"reference":"Practitioner/1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16"}},{"url":"ORC.15","valueString":"20210209"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obr-observation-request","extension":[{"url":"OBR.2","valueIdentifier":{"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}},{"url":"OBR.3","valueIdentifier":{"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}},{"url":"OBR.22","valueString":"202102090000-0600"},{"url":"OBR.16","valueReference":{"reference":"Practitioner/1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBR.17"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}]}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"status":"unknown","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"requester":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.14"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}],"reference":"PractitionerRole/1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b"}}},{"fullUrl":"Practitioner/1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b","resource":{"resourceType":"Practitioner","id":"1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.12"}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}],"address":[{"postalCode":"32174"}]}},{"fullUrl":"Organization/1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3","resource":{"resourceType":"Organization","id":"1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3","name":"<NAME>","telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"407"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"7397506"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"7397506"}]}],"system":"email","use":"work"}],"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"PractitionerRole/1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b","resource":{"resourceType":"PractitionerRole","id":"1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b","practitioner":{"reference":"Practitioner/1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b"},"organization":{"reference":"Organization/1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3"}}},{"fullUrl":"Organization/1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2","resource":{"resourceType":"Organization","id":"1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2","name":"Avante at Ormond Beach"}},{"fullUrl":"Practitioner/1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16","resource":{"resourceType":"Practitioner","id":"1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"Practitioner/1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212","resource":{"resourceType":"Practitioner","id":"1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"DiagnosticReport/1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181","resource":{"resourceType":"DiagnosticReport","id":"1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"basedOn":[{"reference":"ServiceRequest/1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e"}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectivePeriod":{"start":"2021-02-09T00:00:00-06:00","_start":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"end":"2021-02-09T00:00:00-06:00","_end":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},"issued":"2021-02-09T00:00:00-06:00","_issued":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"specimen":[{"reference":"Specimen/1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a"},{"reference":"Specimen/1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce"}],"result":[{"reference":"Observation/1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e"},{"reference":"Observation/1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c"},{"reference":"Observation/1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa"},{"reference":"Observation/1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e"},{"reference":"Observation/1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f"}]}}]}"""
// This message will be parsed and successfully passed through the convert step
// despite having a nonexistent NNN segement and an SFT.2 that is not an ST
@Suppress("ktlint:standard:max-line-length")
private const val invalidHL7Record =
"""MSH|^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT^4^NH|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
NNN|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Suppress("ktlint:standard:max-line-length")
private const val invalidHL7RecordConverted =
"""{"resourceType":"Bundle","id":"1712757037659235000.30975faa-406d-431b-bb27-f2b12211d7e6","meta": {"lastUpdated":"2024-04-10T09:50:37.665-04:00"},"identifier": {"system":"https://reportstream.cdc.gov/prime-router","value":"371784"},"type":"message","timestamp":"2021-02-10T17:07:37.000-05:00","entry":[{"fullUrl":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e","resource":{"resourceType":"MessageHeader","id":"4aeed951-99a9-3152-8885-6b0acc6dd35e","meta":{"tag":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0103","code":"P"}]},"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/msh-message-header","extension":[{"url":"MSH.7","valueString":"20210210170737"},{"url":"MSH.15","valueString":"NE"},{"url":"MSH.16","valueString":"NE"},{"url":"MSH.21","valueIdentifier":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"ELR_Receiver"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.9.11"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"PHLabReportNoAck"}}]}],"eventCoding":{"system":"http://terminology.hl7.org/CodeSystem/v2-0003","code":"R01","display":"ORU^R01^ORU_R01"},"destination":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.5"}],"name":"PRIME_DOH","_endpoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"receiver":{"reference":"Organization/1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52"}}],"sender":{"reference":"Organization/1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a"},"source":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CDC PRIME - Atlanta, Georgia (Dekalb)"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.114222.4.1.237821"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueString":"ISO"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.3"}],"software":"PRIME ReportStream","version":"0.1-SNAPSHOT","endpoint":"urn:oid:2.16.840.1.114222.4.1.237821"}}},{"fullUrl":"Organization/1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a","resource":{"resourceType":"Organization","id":"1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}],"address":[{"country":"USA"}]}},{"fullUrl":"Organization/1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52","resource":{"resourceType":"Organization","id":"1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.6"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Prime ReportStream"}]}},{"fullUrl":"Provenance/1712757038036307000.6751883c-b599-4baf-af74-697462c57974","resource":{"resourceType":"Provenance","id":"1712757038036307000.6751883c-b599-4baf-af74-697462c57974","target":[{"reference":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e"},{"reference":"DiagnosticReport/1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2"}],"recorded":"2021-02-10T17:07:37Z","activity":{"coding":[{"display":"ORU^R01^ORU_R01"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"author"}]},"who":{"reference":"Organization/1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e"}}],"entity":[{"role":"source","what":{"reference":"Device/1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900"}}]}},{"fullUrl":"Organization/1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e","resource":{"resourceType":"Organization","id":"1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}]}},{"fullUrl":"Organization/1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376","resource":{"resourceType":"Organization","id":"1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376","name":"Centers for Disease Control and Prevention"}},{"fullUrl":"Device/1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900","resource":{"resourceType":"Device","id":"1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-vendor-org","valueReference":{"reference":"Organization/1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376"}}],"manufacturer":"Centers for Disease Control and Prevention","deviceName":[{"name":"PRIME ReportStream","type":"manufacturer-name"}],"modelNumber":"0.1-SNAPSHOT","version":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-install-date","valueDateTime":"2021-02-10","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"20210210"}]}}],"value":"0.1-SNAPSHOT"}]}},{"fullUrl":"Provenance/1712757038046070000.62d07304-9ea9-4845-b786-dbc9efce3f4d","resource":{"resourceType":"Provenance","id":"1712757038046070000.62d07304-9ea9-4845-b786-dbc9efce3f4d","recorded":"2024-04-10T09:50:38Z","policy":["http://hl7.org/fhir/uv/v2mappings/message-oru-r01-to-bundle"],"activity":{"coding":[{"code":"v2-FHIR transformation"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"assembler"}]},"who":{"reference":"Organization/1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc"}}]}},{"fullUrl":"Organization/1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc","resource":{"resourceType":"Organization","id":"1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc","identifier":[{"value":"CDC PRIME - Atlanta"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301"}]},"system":"urn:ietf:rfc:3986","value":"2.16.840.1.114222.4.1.237821"}]}},{"fullUrl":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4","resource":{"resourceType":"Patient","id":"1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/pid-patient","extension":[{"url":"PID.8","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"}],"code":"F"}]}},{"url":"PID.30","valueString":"N"}]},{"url":"http://ibm.com/fhir/cdm/StructureDefinition/local-race-cd","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70005"}],"system":"http://terminology.hl7.org/CodeSystem/v3-Race","version":"2.5.1","code":"2106-3","display":"White"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/ethnic-group","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70189"}],"system":"http://terminology.hl7.org/CodeSystem/v2-0189","code":"U","display":"Unknown"}]}}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cx-identifier","extension":[{"url":"CX.5","valueString":"PI"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"PID.3"}],"type":{"coding":[{"code":"PI"}]},"value":"2a14112c-ece1-4f82-915c-7b3a8d152eda","assigner":{"reference":"Organization/1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd"}}],"name":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xpn-human-name","extension":[{"url":"XPN.2","valueString":"Kareem"},{"url":"XPN.3","valueString":"Millie"},{"url":"XPN.7","valueString":"L"}]}],"use":"official","family":"Buckridge","given":["Kareem","Millie"]}],"telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"211"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"2240784"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.1","valueString":"7275555555:1:"},{"url":"XTN.2","valueString":"PRN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"2240784"}]}],"system":"email","use":"home"}],"gender":"female","birthDate":"1958-08-10","_birthDate":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"19580810"}]},"deceasedBoolean":false,"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"688 Leighann Inlet"}]}]}],"line":["688 Leighann Inlet"],"city":"South Rodneychester","district":"48077","state":"TX","postalCode":"67071"}]}},{"fullUrl":"Organization/1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd","resource":{"resourceType":"Organization","id":"1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"}]}},{"fullUrl":"Provenance/1712757038072299000.6792fd4c-14ec-427d-be23-69f7b52770c4","resource":{"resourceType":"Provenance","id":"1712757038072299000.6792fd4c-14ec-427d-be23-69f7b52770c4","target":[{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"}],"recorded":"2024-04-10T09:50:38Z","activity":{"coding":[{"system":"https://terminology.hl7.org/CodeSystem/v3-DataOperation","code":"UPDATE"}]}}},{"fullUrl":"Observation/1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf","resource":{"resourceType":"Observation","id":"1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/analysis-date-time","valueDateTime":"2021-02-09T00:00:00-06:00","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"},{"url":"OBX.17","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"performer":[{"reference":"Organization/1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484"}],"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"260415000","display":"Not detected"}]},"interpretation":[{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70078"}],"code":"N","display":"Normal (applies to non-numeric results)"}]}],"method":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}},{"fullUrl":"Organization/1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484","resource":{"resourceType":"Organization","id":"1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xon-organization","extension":[{"url":"XON.10","valueString":"10D0876999"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBX.25"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CLIA"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.4.7"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"10D0876999"}],"name":"Avante at Ormond Beach","address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"Observation/1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290","resource":{"resourceType":"Observation","id":"1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95418-0","display":"Whether patient is employed in a healthcare setting"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec","resource":{"resourceType":"Observation","id":"1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95417-2","display":"First test for condition of interest"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d","resource":{"resourceType":"Observation","id":"1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95421-4","display":"Resides in a congregate care setting"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Specimen/1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46","resource":{"resourceType":"Specimen","id":"1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"OBR"}]}},{"fullUrl":"Specimen/1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016","resource":{"resourceType":"Specimen","id":"1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"SPM"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Component","valueString":"SPM.2.1"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PGN"}]},"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}],"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"258500001","display":"Nasopharyngeal swab"}]},"receivedTime":"2021-02-09T00:00:00-06:00","_receivedTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"collection":{"collectedDateTime":"2021-02-09T00:00:00-06:00","_collectedDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"bodySite":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","version":"2020-09-01","code":"71836000","display":"Nasopharyngeal structure (body structure)"}]}}}},{"fullUrl":"ServiceRequest/1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494","resource":{"resourceType":"ServiceRequest","id":"1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/business-event","valueCode":"RE"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/orc-common-order","extension":[{"url":"orc-21-ordering-facility-name","valueReference":{"reference":"Organization/1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34"}},{"url":"orc-22-ordering-facility-address","valueAddress":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}},{"url":"orc-24-ordering-provider-address","valueAddress":{"postalCode":"32174"}},{"url":"orc-12-ordering-provider","valueReference":{"reference":"Practitioner/1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da"}},{"url":"ORC.15","valueString":"20210209"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obr-observation-request","extension":[{"url":"OBR.2","valueIdentifier":{"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}},{"url":"OBR.3","valueIdentifier":{"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}},{"url":"OBR.22","valueString":"202102090000-0600"},{"url":"OBR.16","valueReference":{"reference":"Practitioner/1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBR.17"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}]}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"status":"unknown","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"requester":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.14"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}],"reference":"PractitionerRole/1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490"}}},{"fullUrl":"Practitioner/1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c","resource":{"resourceType":"Practitioner","id":"1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.12"}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}],"address":[{"postalCode":"32174"}]}},{"fullUrl":"Organization/1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce","resource":{"resourceType":"Organization","id":"1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce","name":"Avante at Ormond Beach","telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"407"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"7397506"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"7397506"}]}],"system":"email","use":"work"}],"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"PractitionerRole/1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490","resource":{"resourceType":"PractitionerRole","id":"1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490","practitioner":{"reference":"Practitioner/1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c"},"organization":{"reference":"Organization/1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce"}}},{"fullUrl":"Organization/1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34","resource":{"resourceType":"Organization","id":"1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34","name":"Avante at Ormond Beach"}},{"fullUrl":"Practitioner/1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da","resource":{"resourceType":"Practitioner","id":"1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"Practitioner/1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a","resource":{"resourceType":"Practitioner","id":"1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"DiagnosticReport/1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2","resource":{"resourceType":"DiagnosticReport","id":"1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"basedOn":[{"reference":"ServiceRequest/1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494"}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectivePeriod":{"start":"2021-02-09T00:00:00-06:00","_start":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"end":"2021-02-09T00:00:00-06:00","_end":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},"issued":"2021-02-09T00:00:00-06:00","_issued":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"specimen":[{"reference":"Specimen/1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016"},{"reference":"Specimen/1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46"}],"result":[{"reference":"Observation/1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf"},{"reference":"Observation/1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290"},{"reference":"Observation/1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec"},{"reference":"Observation/1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d"}]}}]}"""
// The encoding ^~\&#! make this message not parseable
@Suppress("ktlint:standard:max-line-length")
private const val badEncodingHL7Record =
"""MSH|^~\&#!|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
// The missing | MSH^~\& make this message not parseable
@Suppress("ktlint:standard:max-line-length")
private const val unparseableHL7Record =
"""MSH^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85^6^7^8&F^9|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Testcontainers
@ExtendWith(ReportStreamTestDatabaseSetupExtension::class)
class FhirFunctionIntegrationTests() {
@Container
val azuriteContainer = TestcontainersUtils.createAzuriteContainer(
customImageName = "azurite_fhirfunctionintegration1",
customEnv = mapOf(
"AZURITE_ACCOUNTS" to "devstoreaccount1:keydevstoreaccount1"
)
)
val oneOrganization = DeepOrganization(
"phd", "test", Organization.Jurisdiction.FEDERAL,
receivers = listOf(
Receiver(
"elr",
"phd",
Topic.TEST,
CustomerStatus.INACTIVE,
"one",
timing = Receiver.Timing(numberPerDay = 1, maxReportCount = 1, whenEmpty = Receiver.WhenEmpty())
),
Receiver(
"elr2",
"phd",
Topic.FULL_ELR,
CustomerStatus.ACTIVE,
"classpath:/metadata/hl7_mapping/ORU_R01/ORU_R01-base.yml",
timing = Receiver.Timing(numberPerDay = 1, maxReportCount = 1, whenEmpty = Receiver.WhenEmpty()),
jurisdictionalFilter = listOf("true"),
qualityFilter = listOf("true"),
processingModeFilter = listOf("true"),
format = Report.Format.HL7,
)
),
)
private fun makeWorkflowEngine(
metadata: Metadata,
settings: SettingsProvider,
databaseAccess: DatabaseAccess,
): WorkflowEngine {
return spyk(
WorkflowEngine.Builder().metadata(metadata).settingsProvider(settings).databaseAccess(databaseAccess)
.build()
)
}
private fun seedTask(
fileFormat: Report.Format,
currentAction: TaskAction,
nextAction: TaskAction,
nextEventAction: Event.EventAction,
topic: Topic,
taskIndex: Long = 0,
organization: DeepOrganization,
childReport: Report? = null,
bodyURL: String? = null,
): Report {
val report = Report(
fileFormat,
listOf(ClientSource(organization = organization.name, client = "Test Sender")),
1,
metadata = UnitTestUtils.simpleMetadata,
nextAction = nextAction,
topic = topic
)
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val action = Action().setActionName(currentAction)
val actionId = ReportStreamTestDatabaseContainer.testDatabaseAccess.insertAction(txn, action)
report.bodyURL = bodyURL ?: "http://${report.id}.${fileFormat.toString().lowercase()}"
val reportFile = ReportFile().setSchemaTopic(topic).setReportId(report.id)
.setActionId(actionId).setSchemaName("").setBodyFormat(fileFormat.toString()).setItemCount(1)
.setExternalName("test-external-name")
.setBodyUrl(report.bodyURL)
ReportStreamTestDatabaseContainer.testDatabaseAccess.insertReportFile(
reportFile, txn, action
)
if (childReport != null) {
ReportStreamTestDatabaseContainer.testDatabaseAccess
.insertReportLineage(
ReportLineage(
taskIndex,
actionId,
report.id,
childReport.id,
OffsetDateTime.now()
),
txn
)
}
ReportStreamTestDatabaseContainer.testDatabaseAccess.insertTask(
report,
fileFormat.toString().lowercase(),
report.bodyURL,
nextAction = ProcessEvent(
nextEventAction,
report.id,
Options.None,
emptyMap(),
emptyList()
),
txn
)
}
return report
}
@BeforeEach
fun beforeEach() {
clearAllMocks()
}
@AfterEach
fun afterEach() {
clearAllMocks()
}
@Test
fun `test does not update the DB or send messages on an error`() {
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirengine.azure.hl7_record.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} throws RuntimeException("manual error")
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\"" +
":\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirengine.azure.hl7_record.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
assertThrows<RuntimeException> {
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
}
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNull()
}
verify(exactly = 0) {
QueueAccess.sendMessage(any(), any())
}
}
@Test
fun `test successfully processes a convert message for HL7`() {
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirengine.azure.hl7_record.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirengine.azure.hl7_record.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNotNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNotNull()
}
verify(exactly = 1) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
}
@Test
fun `test successfully processes a convert message for bulk HL7 message`() {
val validBatch = cleanHL7Record + "\n" + invalidHL7Record
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns validBatch.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers { BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray()) }
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(validBatch.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(2)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(2)
}
verify(exactly = 2) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
}
verify(exactly = 1) {
BlobAccess.uploadBody(
Report.Format.FHIR,
match { bytes ->
val result = CompareData().compare(
bytes.inputStream(),
cleanHL7RecordConverted.byteInputStream(),
Report.Format.FHIR,
null
)
result.passed
},
any(), any(), any()
)
BlobAccess.uploadBody(
Report.Format.FHIR,
match { bytes ->
val result = CompareData().compare(
bytes.inputStream(),
invalidHL7RecordConverted.byteInputStream(),
Report.Format.FHIR,
null
)
result.passed
},
any(), any(), any()
)
}
}
@Test
fun `test no items routed for HL7 if any in batch are invalid`() {
val validBatch =
cleanHL7Record + "\n" + invalidHL7Record + "\n" + badEncodingHL7Record + "\n" + unparseableHL7Record
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns validBatch.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers { BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray()) }
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(validBatch.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val actionLogger = ActionLogger()
val fhirFunc = FHIRFunctions(
workflowEngine,
actionLogger = actionLogger,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(0)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(0)
assertThat(actionLogger.errors).hasSize(3)
}
verify(exactly = 0) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
}
@Test
fun `test successfully processes a convert message for a bulk (ndjson) FHIR message`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns bulkFhirRecord.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers {
BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray())
}
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val actionLogger = ActionLogger()
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(bulkFhirRecord.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess,
actionLogger = actionLogger
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(2)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(2)
// Expect two errors for the two badly formed bundles
assertThat(actionLogger.errors).hasSize(2)
}
verify(exactly = 2) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
verify(exactly = 1) {
BlobAccess.uploadBody(
Report.Format.FHIR,
bulkFhirRecord.split("\n")[0].trim().toByteArray(),
any(),
any(),
any()
)
BlobAccess.uploadBody(
Report.Format.FHIR,
bulkFhirRecord.split("\n")[1].trim().toByteArray(),
any(),
any(),
any()
)
}
}
@Test
fun `test successfully processes a route message`() {
val reportServiceMock = mockk<ReportService>()
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.FULL_ELR,
0,
oneOrganization
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
val routeFhirBytes =
File(VALID_FHIR_PATH).readBytes()
every {
BlobAccess.downloadBlobAsByteArray(any())
} returns routeFhirBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
every { reportServiceMock.getSenderName(any()) } returns "senderOrg.senderOrgClient"
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRRouter(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = reportServiceMock
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"route\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(routeFhirBytes))}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doRoute(queueMessage, 1, fhirEngine, actionHistory)
val convertTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(convertTask.routedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.translate))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNotNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION
.eq(TaskAction.translate)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNotNull()
}
verify(exactly = 1) {
QueueAccess.sendMessage(elrTranslationQueueName, any())
}
}
/*
Send a FHIR message to an HL7v2 receiver and ensure the message receiver receives is translated to HL7v2
*/
@Test
fun `test successfully processes a translate message when isSendOriginal is false`() {
// set up and seed azure blobstore
val blobConnectionString =
"""DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=keydevstoreaccount1;BlobEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10000
)
}/devstoreaccount1;QueueEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10001
)
}/devstoreaccount1;"""
val blobContainerMetadata = BlobAccess.BlobContainerMetadata(
"container1",
blobConnectionString
)
mockkObject(BlobAccess)
every { BlobAccess getProperty "defaultBlobMetadata" } returns blobContainerMetadata
// upload reports
val receiveBlobName = "receiveBlobName"
val translateFhirBytes = File(
MULTIPLE_TARGETS_FHIR_PATH
).readBytes()
val receiveBlobUrl = BlobAccess.uploadBlob(
receiveBlobName,
translateFhirBytes,
blobContainerMetadata
)
// Seed the steps backwards so report lineage can be correctly generated
val translateReport = seedTask(
Report.Format.FHIR,
TaskAction.translate,
TaskAction.send,
Event.EventAction.SEND,
Topic.ELR_ELIMS,
100,
oneOrganization
)
val routeReport = seedTask(
Report.Format.FHIR,
TaskAction.route,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.ELR_ELIMS,
99,
oneOrganization,
translateReport
)
val convertReport = seedTask(
Report.Format.FHIR,
TaskAction.convert,
TaskAction.route,
Event.EventAction.ROUTE,
Topic.ELR_ELIMS,
98,
oneOrganization,
routeReport
)
val receiveReport = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.ELR_ELIMS,
97,
oneOrganization,
convertReport,
receiveBlobUrl
)
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = spyk(
FHIRTranslator(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = ReportService(ReportGraph(ReportStreamTestDatabaseContainer.testDatabaseAccess))
)
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { QueueAccess.sendMessage(any(), any()) } returns Unit
mockkObject(BlobAccess.BlobContainerMetadata)
every { BlobAccess.BlobContainerMetadata.build("metadata", any()) } returns BlobAccess.BlobContainerMetadata(
"metadata",
blobConnectionString
)
// The topic param of queueMessage is what should determine how the Translate function runs
val queueMessage = "{\"type\":\"translate\",\"reportId\":\"${translateReport.id}\"," +
"\"blobURL\":\"" + receiveBlobUrl +
"\",\"digest\":\"${
BlobAccess.digestToString(
BlobAccess.sha256Digest(
translateFhirBytes
)
)
}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"," +
"\"receiverFullName\":\"phd.elr2\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doTranslate(queueMessage, 1, fhirEngine, actionHistory)
// verify task and report_file tables were updated correctly in the Translate function (new task and new
// record file created)
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val queueTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.batch))
.fetchOneInto(Task.TASK)
assertThat(queueTask).isNotNull()
val sendReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.REPORT_ID
.eq(queueTask!!.reportId)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(sendReportFile).isNotNull()
// verify sendReportFile message does not match the original message from receive step
assertThat(BlobAccess.downloadBlobAsByteArray(sendReportFile!!.bodyUrl, blobContainerMetadata))
.isNotEqualTo(BlobAccess.downloadBlobAsByteArray(receiveReport.bodyURL, blobContainerMetadata))
}
// verify we did not call the sendOriginal function
verify(exactly = 0) {
fhirEngine.sendOriginal(any(), any(), any())
}
// verify we called the sendTranslated function
verify(exactly = 1) {
fhirEngine.sendTranslated(any(), any(), any())
}
// verify sendMessage did not get called because next action should be Batch
verify(exactly = 0) {
QueueAccess.sendMessage(any(), any())
}
}
/*
Send a FHIR message to an HL7v2 receiver and ensure the message receiver receives is the original FHIR and NOT
translated to HL7v2
*/
@Test
fun `test successfully processes a translate message when isSendOriginal is true`() {
// set up and seed azure blobstore
val blobConnectionString =
"""DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=keydevstoreaccount1;BlobEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10000
)
}/devstoreaccount1;QueueEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10001
)
}/devstoreaccount1;"""
val blobContainerMetadata = BlobAccess.BlobContainerMetadata(
"container1",
blobConnectionString
)
mockkObject(BlobAccess)
every { BlobAccess getProperty "defaultBlobMetadata" } returns blobContainerMetadata
// upload reports
val receiveBlobName = "receiveBlobName"
val translateFhirBytes = File(
MULTIPLE_TARGETS_FHIR_PATH
).readBytes()
val receiveBlobUrl = BlobAccess.uploadBlob(
receiveBlobName,
translateFhirBytes,
blobContainerMetadata
)
// Seed the steps backwards so report lineage can be correctly generated
val translateReport = seedTask(
Report.Format.FHIR,
TaskAction.translate,
TaskAction.send,
Event.EventAction.SEND,
Topic.ELR_ELIMS,
100,
oneOrganization
)
val routeReport = seedTask(
Report.Format.FHIR,
TaskAction.route,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.ELR_ELIMS,
99,
oneOrganization,
translateReport
)
val convertReport = seedTask(
Report.Format.FHIR,
TaskAction.convert,
TaskAction.route,
Event.EventAction.ROUTE,
Topic.ELR_ELIMS,
98,
oneOrganization,
routeReport
)
val receiveReport = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.ELR_ELIMS,
97,
oneOrganization,
convertReport,
receiveBlobUrl
)
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = spyk(
FHIRTranslator(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = ReportService(ReportGraph(ReportStreamTestDatabaseContainer.testDatabaseAccess))
)
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { QueueAccess.sendMessage(any(), any()) } returns Unit
// The topic param of queueMessage is what should determine how the Translate function runs
val queueMessage = "{\"type\":\"translate\",\"reportId\":\"${translateReport.id}\"," +
"\"blobURL\":\"" + receiveBlobUrl +
"\",\"digest\":\"${
BlobAccess.digestToString(
BlobAccess.sha256Digest(
translateFhirBytes
)
)
}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"elr-elims\"," +
"\"receiverFullName\":\"phd.elr2\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doTranslate(queueMessage, 1, fhirEngine, actionHistory)
// verify task and report_file tables were updated correctly in the Translate function
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val sendTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.send))
.fetchOneInto(Task.TASK)
assertThat(sendTask).isNotNull()
val sendReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.REPORT_ID
.eq(sendTask!!.reportId)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(sendReportFile).isNotNull()
// verify sendReportFile message matches the original message from receive step
assertThat(BlobAccess.downloadBlobAsByteArray(sendReportFile!!.bodyUrl, blobContainerMetadata))
.isEqualTo(BlobAccess.downloadBlobAsByteArray(receiveReport.bodyURL, blobContainerMetadata))
}
// verify we called the sendOriginal function
verify(exactly = 1) {
fhirEngine.sendOriginal(any(), any(), any())
}
// verify we did not call the sendTranslated function
verify(exactly = 0) {
fhirEngine.sendTranslated(any(), any(), any())
}
// verify sendMessage did get called because next action should be Send since isOriginal skips the batch
// step
verify(exactly = 1) {
QueueAccess.sendMessage(any(), any())
}
}
@Test
fun `test unmapped observation error messages`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
val fhirRecordBytes = fhirengine.azure.fhirRecord.toByteArray()
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirRecordBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirRecordBytes))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val actionLogs = DSL.using(txn)
.select(ActionLog.ACTION_LOG.asterisk())
.from(ActionLog.ACTION_LOG)
.fetchMany()
.map { it.into(gov.cdc.prime.router.azure.db.tables.pojos.ActionLog::class.java) }
assertThat(actionLogs.size).isEqualTo(1)
assertThat(actionLogs[0].size).isEqualTo(2)
assertThat(actionLogs[0].map { it.detail.message }).isEqualTo(
listOf(
"Missing mapping for code(s): 80382-5",
"Missing mapping for code(s): 260373001"
)
)
}
}
@Test
fun `test codeless observation error message`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
val fhirRecordBytes = fhirengine.azure.codelessFhirRecord.toByteArray()
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirRecordBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirRecordBytes))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val actionLogs = DSL.using(txn)
.select(ActionLog.ACTION_LOG.asterisk())
.from(ActionLog.ACTION_LOG).fetchMany()
.map { it.into(gov.cdc.prime.router.azure.db.tables.pojos.ActionLog::class.java) }
assertThat(actionLogs.size).isEqualTo(1)
assertThat(actionLogs[0].size).isEqualTo(1)
assertThat(actionLogs[0][0].detail.message).isEqualTo("Observation missing code")
}
}
}
| 1,389 |
Kotlin
|
39
| 64 |
ecd862e53ce7fd971deea6fd100fa6b3ea49e171
| 135,485 |
prime-reportstream
|
Creative Commons Zero v1.0 Universal
|
prime-router/src/test/kotlin/fhirengine/azure/FhirFunctionIntegrationTests.kt
|
CDCgov
| 304,423,150 | false |
{"Kotlin": 4641633, "CSS": 3370586, "TypeScript": 1490450, "Java": 916549, "HCL": 282617, "MDX": 146323, "PLpgSQL": 77695, "HTML": 69589, "Shell": 66846, "SCSS": 64177, "Smarty": 51325, "RouterOS Script": 17080, "Python": 13706, "Makefile": 8166, "JavaScript": 8115, "Dockerfile": 2304}
|
package fhirengine.azure
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import gov.cdc.prime.router.ActionLogger
import gov.cdc.prime.router.ClientSource
import gov.cdc.prime.router.CustomerStatus
import gov.cdc.prime.router.DeepOrganization
import gov.cdc.prime.router.FileSettings
import gov.cdc.prime.router.Metadata
import gov.cdc.prime.router.Options
import gov.cdc.prime.router.Organization
import gov.cdc.prime.router.Receiver
import gov.cdc.prime.router.Report
import gov.cdc.prime.router.SettingsProvider
import gov.cdc.prime.router.Topic
import gov.cdc.prime.router.azure.ActionHistory
import gov.cdc.prime.router.azure.BlobAccess
import gov.cdc.prime.router.azure.DatabaseAccess
import gov.cdc.prime.router.azure.Event
import gov.cdc.prime.router.azure.ProcessEvent
import gov.cdc.prime.router.azure.QueueAccess
import gov.cdc.prime.router.azure.WorkflowEngine
import gov.cdc.prime.router.azure.db.enums.TaskAction
import gov.cdc.prime.router.azure.db.tables.ActionLog
import gov.cdc.prime.router.azure.db.tables.Task
import gov.cdc.prime.router.azure.db.tables.pojos.Action
import gov.cdc.prime.router.azure.db.tables.pojos.ReportFile
import gov.cdc.prime.router.azure.db.tables.pojos.ReportLineage
import gov.cdc.prime.router.cli.tests.CompareData
import gov.cdc.prime.router.common.TestcontainersUtils
import gov.cdc.prime.router.db.ReportStreamTestDatabaseContainer
import gov.cdc.prime.router.db.ReportStreamTestDatabaseSetupExtension
import gov.cdc.prime.router.fhirengine.azure.FHIRFunctions
import gov.cdc.prime.router.fhirengine.engine.FHIRConverter
import gov.cdc.prime.router.fhirengine.engine.FHIRRouter
import gov.cdc.prime.router.fhirengine.engine.FHIRTranslator
import gov.cdc.prime.router.fhirengine.engine.QueueMessage
import gov.cdc.prime.router.fhirengine.engine.elrRoutingQueueName
import gov.cdc.prime.router.fhirengine.engine.elrTranslationQueueName
import gov.cdc.prime.router.history.db.ReportGraph
import gov.cdc.prime.router.metadata.LookupTable
import gov.cdc.prime.router.report.ReportService
import gov.cdc.prime.router.unittest.UnitTestUtils
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.spyk
import io.mockk.verify
import org.jooq.impl.DSL
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import java.io.File
import java.time.OffsetDateTime
import java.util.UUID
private const val MULTIPLE_TARGETS_FHIR_PATH = "src/test/resources/fhirengine/engine/valid_data_multiple_targets.fhir"
private const val VALID_FHIR_PATH = "src/test/resources/fhirengine/engine/valid_data.fhir"
private const val hl7_record =
"MSH|^~\\&|CDC PRIME - Atlanta,^2.16.840.1.114222.4.1.237821^ISO|Winchester House^05D2222542^" +
"ISO|CDPH FL REDIE^2.16.840.1.114222.4.3.3.10.1.1^ISO|CDPH_CID^2.16.840.1.114222.4.1.214104^ISO|202108031315" +
"11.0147+0000||ORU^R01^ORU_R01|1234d1d1-95fe-462c-8ac6-46728dba581c|P|2.5.1|||NE|NE|USA|UNICODE UTF-8|||PHLab" +
"Report-NoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO\n" +
"SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME Data Hub|0.1-SNAPSHOT||20210726\n" +
"PID|1||09d12345-0987-1234-1234-111b1ee0879f^^^Winchester House&05D2222542&ISO^PI^&05D2222542&ISO||Bunny^Bug" +
"s^C^^^^L||19000101|M||2106-3^White^HL70005^^^^2.5.1|12345 Main St^^San Jose^FL^95125^USA^^^06085||(123)456-" +
"7890^PRN^PH^^1^123^4567890|||||||||N^Non Hispanic or Latino^HL70189^^^^2.9||||||||N\n" +
"ORC|RE|1234d1d1-95fe-462c-8ac6-46728dba581c^Winchester House^05D2222542^ISO|1234d1d1-95fe-462c-8ac6-46728db" +
"a581c^Winchester House^05D2222542^ISO|||||||||1679892871^Doolittle^Doctor^^^^^^CMS&2.16.840.1.113883.3.249&" +
"ISO^^^^NPI||(123)456-7890^WPN^PH^^1^123^4567890|20210802||||||Winchester House|6789 Main St^^San Jose^FL^95" +
"126^^^^06085|(123)456-7890^WPN^PH^^1^123^4567890|6789 Main St^^San Jose^FL^95126\n" +
"OBR|1|1234d1d1-95fe-462c-8ac6-46728dba581c^Winchester House^05D2222542^ISO|1234d1d1-95fe-462c-8ac6-46728dba" +
"581c^Winchester House^05D2222542^ISO|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by" +
" Rapid immunoassay^LN^^^^2.68|||202108020000-0500|202108020000-0500||||||||1679892871^Doolittle^Doctor^^^^" +
"^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|(123)456-7890^WPN^PH^^1^123^4567890|||||202108020000-0500|||F\n" +
"OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN^^^^2." +
"68||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078^^^^2.7|||F|||20210802000" +
"0-0500|05D2222542^ISO||10811877011290_DIT^10811877011290^99ELR^^^^2.68^^10811877011290_DIT||20" +
"2108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D2222542|6789 Main St^^" +
"San Jose^FL^95126^^^^06085\n" +
"OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||N^No^HL70136||||||F|||202" +
"108020000-0500|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX" +
"^^^05D2222542|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202108020000-0500" +
"|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D2222542|" +
"6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202108020000-05" +
"00|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^05D22225" +
"42|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||2021080" +
"20000-0500|05D2222542||||202108020000-0500||||Winchester House^^^^^ISO&2.16.840.1.113883.19.4.6&ISO^XX^^^" +
"05D2222542|6789 Main St^^San Jose^FL^95126-5285^^^^06085|||||QST\n" +
"SPM|1|1234d1d1-95fe-462c-8ac6-46728dba581c&&05D2222542&ISO^1234d1d1-95fe-462c-8ac6-46728dba581c&&05D22225" +
"42&ISO||445297001^Swab of internal nose^SCT^^^^2.67||||53342003^Internal nose structure (body structure)^" +
"SCT^^^^2020-09-01|||||||||202108020000-0500|20210802000006.0000-0500"
@Suppress("ktlint:standard:max-line-length")
private const val fhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}"""
@Suppress("ktlint:standard:max-line-length")
private const val codelessFhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}"""
@Suppress("ktlint:standard:max-line-length")
private const val bulkFhirRecord =
"""{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c12347","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dba581c"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}
{"resourceType":"Bundle","id":"1667861767830636000.7db38d22-b713-49fc-abfa-2edba9c09876","meta":{"lastUpdated":"2022-11-07T22:56:07.832+00:00"},"identifier":{"value":"1234d1d1-95fe-462c-8ac6-46728dbau8cd"},"type":"message","timestamp":"2021-08-03T13:15:11.015+00:00","entry":[{"fullUrl":"Observation/d683b42a-bf50-45e8-9fce-6c0531994f09","resource":{"resourceType":"Observation","id":"d683b42a-bf50-45e8-9fce-6c0531994f09","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"80382-5"}],"text":"Flu A"},"subject":{"reference":"Patient/9473889b-b2b9-45ac-a8d8-191f27132912"},"performer":[{"reference":"Organization/1a0139b9-fc23-450b-9b6c-cd081e5cea9d"}],"valueCodeableConcept":{"coding":[{"system":"http://snomed.info/sct","code":"260373001","display":"Detected"}]},"interpretation":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0078","code":"A","display":"Abnormal"}]}],"method":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/testkit-name-id","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/equipment-uid","valueCoding":{"code":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B_Becton, Dickinson and Company (BD)"}}],"coding":[{"display":"BD Veritor System for Rapid Detection of SARS-CoV-2 & Flu A+B*"}]},"specimen":{"reference":"Specimen/52a582e4-d389-42d0-b738-bee51cf5244d"},"device":{"reference":"Device/78dc4d98-2958-43a3-a445-76ceef8c0698"}}}]}
{}
{"resourceType":"Bund}"""
@Suppress("ktlint:standard:max-line-length")
private const val cleanHL7Record =
"""MSH|^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Suppress("ktlint:standard:max-line-length")
private const val cleanHL7RecordConverted =
"""{"resourceType":"Bundle","id":"1712756879851727000.c7991c94-bacb-4339-9574-6cdd2070cdc1","meta":{"lastUpdated":"2024-04-10T09:47:59.857-04:00"},"identifier":{"system":"https://reportstream.cdc.gov/prime-router","value":"371784"},"type":"message","timestamp":"2021-02-10T17:07:37.000-05:00","entry":[{"fullUrl":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e","resource":{"resourceType":"MessageHeader","id":"4aeed951-99a9-3152-8885-6b0acc6dd35e","meta":{"tag":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0103","code":"P"}]},"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/msh-message-header","extension":[{"url":"MSH.7","valueString":"20210210170737"},{"url":"MSH.15","valueString":"NE"},{"url":"MSH.16","valueString":"NE"},{"url":"MSH.21","valueIdentifier":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"ELR_Receiver"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.9.11"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"PHLabReportNoAck"}}]}],"eventCoding":{"system":"http://terminology.hl7.org/CodeSystem/v2-0003","code":"R01","display":"ORU^R01^ORU_R01"},"destination":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.5"}],"name":"PRIME_DOH","_endpoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"receiver":{"reference":"Organization/1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9"}}],"sender":{"reference":"Organization/1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1"},"source":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CDC PRIME - Atlanta, Georgia (Dekalb)"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.114222.4.1.237821"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueString":"ISO"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.3"}],"software":"PRIME ReportStream","version":"0.1-SNAPSHOT","endpoint":"urn:oid:2.16.840.1.114222.4.1.237821"}}},{"fullUrl":"Organization/1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1","resource":{"resourceType":"Organization","id":"1712756879895760000.c237e774-4799-46a5-8bed-16a30bf29de1","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}],"address":[{"country":"USA"}]}},{"fullUrl":"Organization/1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9","resource":{"resourceType":"Organization","id":"1712756879919243000.ba39b13e-fba9-4998-8424-9041d87015b9","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.6"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Prime ReportStream"}]}},{"fullUrl":"Provenance/1712756880222129000.288337a9-f487-4208-94a3-7c93996d1161","resource":{"resourceType":"Provenance","id":"1712756880222129000.288337a9-f487-4208-94a3-7c93996d1161","target":[{"reference":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e"},{"reference":"DiagnosticReport/1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181"}],"recorded":"2021-02-10T17:07:37Z","activity":{"coding":[{"display":"ORU^R01^ORU_R01"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"author"}]},"who":{"reference":"Organization/1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3"}}],"entity":[{"role":"source","what":{"reference":"Device/1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d"}}]}},{"fullUrl":"Organization/1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3","resource":{"resourceType":"Organization","id":"1712756880221441000.fc220020-4a56-42db-9462-e599c51de1c3","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}]}},{"fullUrl":"Organization/1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c","resource":{"resourceType":"Organization","id":"1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c","name":"Centers for Disease Control and Prevention"}},{"fullUrl":"Device/1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d","resource":{"resourceType":"Device","id":"1712756880226075000.0efb9a02-eed4-4f77-a83e-8f9d555d870d","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-vendor-org","valueReference":{"reference":"Organization/1712756880225828000.b20d6836-7a09-4d20-85da-3d97b759885c"}}],"manufacturer":"Centers for Disease Control and Prevention","deviceName":[{"name":"PRIME ReportStream","type":"manufacturer-name"}],"modelNumber":"0.1-SNAPSHOT","version":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-install-date","valueDateTime":"2021-02-10","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"20210210"}]}}],"value":"0.1-SNAPSHOT"}]}},{"fullUrl":"Provenance/1712756880233764000.4cf51f91-0e13-467e-8861-1e4ad2899343","resource":{"resourceType":"Provenance","id":"1712756880233764000.4cf51f91-0e13-467e-8861-1e4ad2899343","recorded":"2024-04-10T09:48:00Z","policy":["http://hl7.org/fhir/uv/v2mappings/message-oru-r01-to-bundle"],"activity":{"coding":[{"code":"v2-FHIR transformation"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"assembler"}]},"who":{"reference":"Organization/1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f"}}]}},{"fullUrl":"Organization/1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f","resource":{"resourceType":"Organization","id":"1712756880233374000.9f158398-668e-4160-830f-96fa95cd818f","identifier":[{"value":"CDC PRIME - Atlanta"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301"}]},"system":"urn:ietf:rfc:3986","value":"2.16.840.1.114222.4.1.237821"}]}},{"fullUrl":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9","resource":{"resourceType":"Patient","id":"1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/pid-patient","extension":[{"url":"PID.8","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"}],"code":"F"}]}},{"url":"PID.30","valueString":"N"}]},{"url":"http://ibm.com/fhir/cdm/StructureDefinition/local-race-cd","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70005"}],"system":"http://terminology.hl7.org/CodeSystem/v3-Race","version":"2.5.1","code":"2106-3","display":"White"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/ethnic-group","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70189"}],"system":"http://terminology.hl7.org/CodeSystem/v2-0189","code":"U","display":"Unknown"}]}}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cx-identifier","extension":[{"url":"CX.5","valueString":"PI"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"PID.3"}],"type":{"coding":[{"code":"PI"}]},"value":"2a14112c-ece1-4f82-915c-7b3a8d152eda","assigner":{"reference":"Organization/1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca"}}],"name":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xpn-human-name","extension":[{"url":"XPN.2","valueString":"Kareem"},{"url":"XPN.3","valueString":"Millie"},{"url":"XPN.7","valueString":"L"}]}],"use":"official","family":"Buckridge","given":["Kareem","Millie"]}],"telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"211"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"2240784"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.1","valueString":"7275555555:1:"},{"url":"XTN.2","valueString":"PRN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"2240784"}]}],"system":"email","use":"home"}],"gender":"female","birthDate":"1958-08-10","_birthDate":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"19580810"}]},"deceasedBoolean":false,"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"688 Leighann Inlet"}]}]}],"line":["688 Leighann Inlet"],"city":"South Rodneychester","district":"48077","state":"TX","postalCode":"67071"}]}},{"fullUrl":"Organization/1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca","resource":{"resourceType":"Organization","id":"1712756880240394000.64920944-7de7-4c3e-bf74-441fc207f2ca","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"}]}},{"fullUrl":"Provenance/1712756880258584000.921c8787-5833-457c-a27f-b335a02cb038","resource":{"resourceType":"Provenance","id":"1712756880258584000.921c8787-5833-457c-a27f-b335a02cb038","target":[{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"}],"recorded":"2024-04-10T09:48:00Z","activity":{"coding":[{"system":"https://terminology.hl7.org/CodeSystem/v3-DataOperation","code":"UPDATE"}]}}},{"fullUrl":"Observation/1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e","resource":{"resourceType":"Observation","id":"1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/analysis-date-time","valueDateTime":"2021-02-09T00:00:00-06:00","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"},{"url":"OBX.17","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"performer":[{"reference":"Organization/1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43"}],"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"260415000","display":"Not detected"}]},"interpretation":[{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70078"}],"code":"N","display":"Normal (applies to non-numeric results)"}]}],"method":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}},{"fullUrl":"Organization/1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43","resource":{"resourceType":"Organization","id":"1712756880262594000.c8a20886-b7dd-4c49-825f-4ee246b16e43","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xon-organization","extension":[{"url":"XON.10","valueString":"10D0876999"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBX.25"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CLIA"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.4.7"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"10D0876999"}],"name":"Avante at Ormond Beach","address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"Observation/1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c","resource":{"resourceType":"Observation","id":"1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95418-0","display":"Whether patient is employed in a healthcare setting"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa","resource":{"resourceType":"Observation","id":"1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95417-2","display":"First test for condition of interest"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e","resource":{"resourceType":"Observation","id":"1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95421-4","display":"Resides in a congregate care setting"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Observation/1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f","resource":{"resourceType":"Observation","id":"1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95419-8","display":"Has symptoms related to condition of interest"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Specimen/1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce","resource":{"resourceType":"Specimen","id":"1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"OBR"}]}},{"fullUrl":"Specimen/1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a","resource":{"resourceType":"Specimen","id":"1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"SPM"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Component","valueString":"SPM.2.1"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PGN"}]},"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}],"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"258500001","display":"Nasopharyngeal swab"}]},"receivedTime":"2021-02-09T00:00:00-06:00","_receivedTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"collection":{"collectedDateTime":"2021-02-09T00:00:00-06:00","_collectedDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"bodySite":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","version":"2020-09-01","code":"71836000","display":"Nasopharyngeal structure (body structure)"}]}}}},{"fullUrl":"ServiceRequest/1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e","resource":{"resourceType":"ServiceRequest","id":"1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/business-event","valueCode":"RE"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/orc-common-order","extension":[{"url":"orc-21-ordering-facility-name","valueReference":{"reference":"Organization/1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2"}},{"url":"orc-22-ordering-facility-address","valueAddress":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}},{"url":"orc-24-ordering-provider-address","valueAddress":{"postalCode":"32174"}},{"url":"orc-12-ordering-provider","valueReference":{"reference":"Practitioner/1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16"}},{"url":"ORC.15","valueString":"20210209"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obr-observation-request","extension":[{"url":"OBR.2","valueIdentifier":{"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}},{"url":"OBR.3","valueIdentifier":{"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}},{"url":"OBR.22","valueString":"202102090000-0600"},{"url":"OBR.16","valueReference":{"reference":"Practitioner/1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBR.17"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}]}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"status":"unknown","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"requester":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.14"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}],"reference":"PractitionerRole/1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b"}}},{"fullUrl":"Practitioner/1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b","resource":{"resourceType":"Practitioner","id":"1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.12"}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}],"address":[{"postalCode":"32174"}]}},{"fullUrl":"Organization/1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3","resource":{"resourceType":"Organization","id":"1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3","name":"<NAME>","telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"407"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"7397506"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"7397506"}]}],"system":"email","use":"work"}],"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"PractitionerRole/1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b","resource":{"resourceType":"PractitionerRole","id":"1712756880431226000.9aa4ae44-bf1c-463a-9d6d-74b301fd5d9b","practitioner":{"reference":"Practitioner/1712756880432296000.a0f993c1-d53e-4096-b4d9-53ff76b7dc9b"},"organization":{"reference":"Organization/1712756880433400000.5b784cae-d586-4aad-8618-c8e10a7ce0f3"}}},{"fullUrl":"Organization/1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2","resource":{"resourceType":"Organization","id":"1712756880434870000.ff1f93c1-fd60-48bc-97e3-b810150d3ee2","name":"Avante at Ormond Beach"}},{"fullUrl":"Practitioner/1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16","resource":{"resourceType":"Practitioner","id":"1712756880436254000.45c69b0f-e8a7-4e9e-a532-36dd7fc07f16","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"Practitioner/1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212","resource":{"resourceType":"Practitioner","id":"1712756880438139000.e51d0798-dd38-46a4-981a-4c4c510f3212","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"DiagnosticReport/1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181","resource":{"resourceType":"DiagnosticReport","id":"1712756880443318000.19bb7060-610a-4330-abf6-643b2e35f181","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"basedOn":[{"reference":"ServiceRequest/1712756880439324000.3ea1d4fc-cea3-445d-b549-8dd888aee43e"}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712756880256190000.9a0915c3-304a-4c00-b587-cf4b45e459a9"},"effectivePeriod":{"start":"2021-02-09T00:00:00-06:00","_start":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"end":"2021-02-09T00:00:00-06:00","_end":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},"issued":"2021-02-09T00:00:00-06:00","_issued":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"specimen":[{"reference":"Specimen/1712756880430178000.b590c564-eae2-4b18-ba72-175c1dd9a73a"},{"reference":"Specimen/1712756880428620000.f302488a-bbc6-4d93-b749-dd3a6e0597ce"}],"result":[{"reference":"Observation/1712756880261604000.11f38918-c93b-4f15-adaa-4612667d820e"},{"reference":"Observation/1712756880265283000.1c513855-b095-4cdb-841e-4dc8a9b7948c"},{"reference":"Observation/1712756880267026000.7ff1a74b-523c-4afa-8387-9c8eee8ab0aa"},{"reference":"Observation/1712756880268657000.0aa3c682-784e-4f57-858c-3c6e2457ef6e"},{"reference":"Observation/1712756880270043000.ba8502fb-2629-4223-b9ba-8d8391691f8f"}]}}]}"""
// This message will be parsed and successfully passed through the convert step
// despite having a nonexistent NNN segement and an SFT.2 that is not an ST
@Suppress("ktlint:standard:max-line-length")
private const val invalidHL7Record =
"""MSH|^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT^4^NH|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
NNN|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Suppress("ktlint:standard:max-line-length")
private const val invalidHL7RecordConverted =
"""{"resourceType":"Bundle","id":"1712757037659235000.30975faa-406d-431b-bb27-f2b12211d7e6","meta": {"lastUpdated":"2024-04-10T09:50:37.665-04:00"},"identifier": {"system":"https://reportstream.cdc.gov/prime-router","value":"371784"},"type":"message","timestamp":"2021-02-10T17:07:37.000-05:00","entry":[{"fullUrl":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e","resource":{"resourceType":"MessageHeader","id":"4aeed951-99a9-3152-8885-6b0acc6dd35e","meta":{"tag":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0103","code":"P"}]},"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/msh-message-header","extension":[{"url":"MSH.7","valueString":"20210210170737"},{"url":"MSH.15","valueString":"NE"},{"url":"MSH.16","valueString":"NE"},{"url":"MSH.21","valueIdentifier":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"ELR_Receiver"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.9.11"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"PHLabReportNoAck"}}]}],"eventCoding":{"system":"http://terminology.hl7.org/CodeSystem/v2-0003","code":"R01","display":"ORU^R01^ORU_R01"},"destination":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.5"}],"name":"PRIME_DOH","_endpoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"receiver":{"reference":"Organization/1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52"}}],"sender":{"reference":"Organization/1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a"},"source":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CDC PRIME - Atlanta, Georgia (Dekalb)"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.114222.4.1.237821"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueString":"ISO"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.3"}],"software":"PRIME ReportStream","version":"0.1-SNAPSHOT","endpoint":"urn:oid:2.16.840.1.114222.4.1.237821"}}},{"fullUrl":"Organization/1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a","resource":{"resourceType":"Organization","id":"1712757037704001000.795452c4-9e66-4386-a4ec-ead3574a2c4a","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}],"address":[{"country":"USA"}]}},{"fullUrl":"Organization/1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52","resource":{"resourceType":"Organization","id":"1712757037738116000.d068a62a-085e-4178-9449-070dc1bc4c52","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"MSH.6"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Prime ReportStream"}]}},{"fullUrl":"Provenance/1712757038036307000.6751883c-b599-4baf-af74-697462c57974","resource":{"resourceType":"Provenance","id":"1712757038036307000.6751883c-b599-4baf-af74-697462c57974","target":[{"reference":"MessageHeader/4aeed951-99a9-3152-8885-6b0acc6dd35e"},{"reference":"DiagnosticReport/1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2"}],"recorded":"2021-02-10T17:07:37Z","activity":{"coding":[{"display":"ORU^R01^ORU_R01"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"author"}]},"who":{"reference":"Organization/1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e"}}],"entity":[{"role":"source","what":{"reference":"Device/1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900"}}]}},{"fullUrl":"Organization/1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e","resource":{"resourceType":"Organization","id":"1712757038035736000.cb799a68-cfdc-4f8b-b855-46947b35ce7e","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.2,HD.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301","code":"CLIA"}]},"value":"10D0876999"}]}},{"fullUrl":"Organization/1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376","resource":{"resourceType":"Organization","id":"1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376","name":"Centers for Disease Control and Prevention"}},{"fullUrl":"Device/1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900","resource":{"resourceType":"Device","id":"1712757038039628000.79cd1bf0-a8ec-4744-a8ca-7f87ce665900","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-vendor-org","valueReference":{"reference":"Organization/1712757038039431000.8ff0c13b-32df-48ff-b4e2-b937e8eb4376"}}],"manufacturer":"Centers for Disease Control and Prevention","deviceName":[{"name":"PRIME ReportStream","type":"manufacturer-name"}],"modelNumber":"0.1-SNAPSHOT","version":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/software-install-date","valueDateTime":"2021-02-10","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"20210210"}]}}],"value":"0.1-SNAPSHOT"}]}},{"fullUrl":"Provenance/1712757038046070000.62d07304-9ea9-4845-b786-dbc9efce3f4d","resource":{"resourceType":"Provenance","id":"1712757038046070000.62d07304-9ea9-4845-b786-dbc9efce3f4d","recorded":"2024-04-10T09:50:38Z","policy":["http://hl7.org/fhir/uv/v2mappings/message-oru-r01-to-bundle"],"activity":{"coding":[{"code":"v2-FHIR transformation"}]},"agent":[{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/provenance-participant-type","code":"assembler"}]},"who":{"reference":"Organization/1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc"}}]}},{"fullUrl":"Organization/1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc","resource":{"resourceType":"Organization","id":"1712757038045747000.a08e6443-075d-43ea-becb-3da7727353dc","identifier":[{"value":"CDC PRIME - Atlanta"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0301"}]},"system":"urn:ietf:rfc:3986","value":"2.16.840.1.114222.4.1.237821"}]}},{"fullUrl":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4","resource":{"resourceType":"Patient","id":"1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/pid-patient","extension":[{"url":"PID.8","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"}],"code":"F"}]}},{"url":"PID.30","valueString":"N"}]},{"url":"http://ibm.com/fhir/cdm/StructureDefinition/local-race-cd","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70005"}],"system":"http://terminology.hl7.org/CodeSystem/v3-Race","version":"2.5.1","code":"2106-3","display":"White"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/ethnic-group","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70189"}],"system":"http://terminology.hl7.org/CodeSystem/v2-0189","code":"U","display":"Unknown"}]}}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cx-identifier","extension":[{"url":"CX.5","valueString":"PI"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"PID.3"}],"type":{"coding":[{"code":"PI"}]},"value":"2a14112c-ece1-4f82-915c-7b3a8d152eda","assigner":{"reference":"Organization/1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd"}}],"name":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xpn-human-name","extension":[{"url":"XPN.2","valueString":"Kareem"},{"url":"XPN.3","valueString":"Millie"},{"url":"XPN.7","valueString":"L"}]}],"use":"official","family":"Buckridge","given":["Kareem","Millie"]}],"telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"211"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"2240784"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.1","valueString":"7275555555:1:"},{"url":"XTN.2","valueString":"PRN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"2240784"}]}],"system":"email","use":"home"}],"gender":"female","birthDate":"1958-08-10","_birthDate":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"19580810"}]},"deceasedBoolean":false,"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"688 Leighann Inlet"}]}]}],"line":["688 Leighann Inlet"],"city":"South Rodneychester","district":"48077","state":"TX","postalCode":"67071"}]}},{"fullUrl":"Organization/1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd","resource":{"resourceType":"Organization","id":"1712757038052890000.58a63490-6901-4580-9397-95be1e6d87bd","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"HD.1"}],"value":"Avante at Ormond Beach"}]}},{"fullUrl":"Provenance/1712757038072299000.6792fd4c-14ec-427d-be23-69f7b52770c4","resource":{"resourceType":"Provenance","id":"1712757038072299000.6792fd4c-14ec-427d-be23-69f7b52770c4","target":[{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"}],"recorded":"2024-04-10T09:50:38Z","activity":{"coding":[{"system":"https://terminology.hl7.org/CodeSystem/v3-DataOperation","code":"UPDATE"}]}}},{"fullUrl":"Observation/1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf","resource":{"resourceType":"Observation","id":"1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/analysis-date-time","valueDateTime":"2021-02-09T00:00:00-06:00","_valueDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"},{"url":"OBX.17","valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"performer":[{"reference":"Organization/1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484"}],"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"260415000","display":"Not detected"}]},"interpretation":[{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70078"}],"code":"N","display":"Normal (applies to non-numeric results)"}]}],"method":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"99ELR"}],"code":"CareStart COVID-19 Antigen test_Access Bio, Inc._EUA"}]}}},{"fullUrl":"Organization/1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484","resource":{"resourceType":"Organization","id":"1712757038076224000.0547dc9f-b687-4718-89f2-35cab97ab484","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xon-organization","extension":[{"url":"XON.10","valueString":"10D0876999"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBX.25"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CLIA"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.4.7"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]}],"value":"10D0876999"}],"name":"Avante at Ormond Beach","address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"Observation/1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290","resource":{"resourceType":"Observation","id":"1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95418-0","display":"Whether patient is employed in a healthcare setting"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec","resource":{"resourceType":"Observation","id":"1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95417-2","display":"First test for condition of interest"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"Y","display":"Yes"}]}}},{"fullUrl":"Observation/1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d","resource":{"resourceType":"Observation","id":"1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obx-observation","extension":[{"url":"OBX.2","valueId":"CWE"},{"url":"OBX.11","valueString":"F"}]}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","version":"2.69","code":"95421-4","display":"Resides in a congregate care setting"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectiveDateTime":"2021-02-09T00:00:00-06:00","_effectiveDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"valueCodeableConcept":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"HL70136"}],"code":"N","display":"No"}]}}},{"fullUrl":"Specimen/1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46","resource":{"resourceType":"Specimen","id":"1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"OBR"}]}},{"fullUrl":"Specimen/1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016","resource":{"resourceType":"Specimen","id":"1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Segment","valueString":"SPM"}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Component","valueString":"SPM.2.1"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PGN"}]},"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}],"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","code":"258500001","display":"Nasopharyngeal swab"}]},"receivedTime":"2021-02-09T00:00:00-06:00","_receivedTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"collection":{"collectedDateTime":"2021-02-09T00:00:00-06:00","_collectedDateTime":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"bodySite":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"SCT"}],"system":"http://snomed.info/sct","version":"2020-09-01","code":"71836000","display":"Nasopharyngeal structure (body structure)"}]}}}},{"fullUrl":"ServiceRequest/1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494","resource":{"resourceType":"ServiceRequest","id":"1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/business-event","valueCode":"RE"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/orc-common-order","extension":[{"url":"orc-21-ordering-facility-name","valueReference":{"reference":"Organization/1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34"}},{"url":"orc-22-ordering-facility-address","valueAddress":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}},{"url":"orc-24-ordering-provider-address","valueAddress":{"postalCode":"32174"}},{"url":"orc-12-ordering-provider","valueReference":{"reference":"Practitioner/1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da"}},{"url":"ORC.15","valueString":"20210209"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/obr-observation-request","extension":[{"url":"OBR.2","valueIdentifier":{"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}},{"url":"OBR.3","valueIdentifier":{"value":"0cba76f5-35e0-4a28-803a-2f31308aae9b"}},{"url":"OBR.22","valueString":"202102090000-0600"},{"url":"OBR.16","valueReference":{"reference":"Practitioner/1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a"}},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"OBR.17"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}]}],"identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.3"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"status":"unknown","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"requester":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/callback-number","valueContactPoint":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"386"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"6825220"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.7","valueString":"6825220"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.14"}],"_system":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/data-absent-reason","valueCode":"unknown"}]},"use":"work"}}],"reference":"PractitionerRole/1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490"}}},{"fullUrl":"Practitioner/1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c","resource":{"resourceType":"Practitioner","id":"1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.12"}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}],"address":[{"postalCode":"32174"}]}},{"fullUrl":"Organization/1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce","resource":{"resourceType":"Organization","id":"1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce","name":"Avante at Ormond Beach","telecom":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-country","valueString":"1"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-area","valueString":"407"},{"url":"http://hl7.org/fhir/StructureDefinition/contactpoint-local","valueString":"7397506"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xtn-contact-point","extension":[{"url":"XTN.2","valueString":"WPN"},{"url":"XTN.4","valueString":"<EMAIL>"},{"url":"XTN.7","valueString":"7397506"}]}],"system":"email","use":"work"}],"address":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xad-address","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/sad-address-line","extension":[{"url":"SAD.1","valueString":"170 North King Road"}]}]}],"line":["170 North King Road"],"city":"Ormond Beach","district":"12127","state":"FL","postalCode":"32174"}]}},{"fullUrl":"PractitionerRole/1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490","resource":{"resourceType":"PractitionerRole","id":"1712757038261643000.6efb53bb-f1b8-41b6-b0f3-882bb77ae490","practitioner":{"reference":"Practitioner/1712757038263290000.2f1094f8-9102-47a4-ae7b-7b5f92939c3c"},"organization":{"reference":"Organization/1712757038264599000.cc220948-c6ff-4033-bb9a-2e5f298a0dce"}}},{"fullUrl":"Organization/1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34","resource":{"resourceType":"Organization","id":"1712757038266629000.8c5cae2d-9a85-4ac3-a132-20eacd147b34","name":"Avante at Ormond Beach"}},{"fullUrl":"Practitioner/1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da","resource":{"resourceType":"Practitioner","id":"1712757038268099000.82988aae-a3f9-4c86-b5a6-551f138137da","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"Practitioner/1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a","resource":{"resourceType":"Practitioner","id":"1712757038269272000.3fb6fb88-8f55-4cd0-90ce-1f6ae370261a","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/assigning-authority","extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/namespace-id","valueString":"CMS"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id","valueString":"2.16.840.1.113883.3.249"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/universal-id-type","valueCode":"ISO"}]},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/xcn-practitioner","extension":[{"url":"XCN.3","valueString":"Husam"}]}],"identifier":[{"type":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/codeable-concept-id","valueBoolean":true}],"code":"NPI"}]},"system":"CMS","value":"1629082607"}],"name":[{"family":"Eddin","given":["Husam"]}]}},{"fullUrl":"DiagnosticReport/1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2","resource":{"resourceType":"DiagnosticReport","id":"1712757038276055000.731339d8-ad84-4544-bf1e-6ecc94bbbbb2","identifier":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2Field","valueString":"ORC.2"}],"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"PLAC"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"},{"type":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/v2-0203","code":"FILL"}]},"value":"73a6e9bd-aaec-418e-813a-0ad33366ca85"}],"basedOn":[{"reference":"ServiceRequest/1712757038270693000.1da2094d-51d3-4a48-82cb-45c3c23d8494"}],"status":"final","code":{"coding":[{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding","valueString":"coding"},{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/cwe-coding-system","valueString":"LN"}],"system":"http://loinc.org","code":"94558-4","display":"SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay"}]},"subject":{"reference":"Patient/1712757038069389000.c326d5d6-6a81-49a7-a8d7-f31d1e962bb4"},"effectivePeriod":{"start":"2021-02-09T00:00:00-06:00","_start":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"end":"2021-02-09T00:00:00-06:00","_end":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]}},"issued":"2021-02-09T00:00:00-06:00","_issued":{"extension":[{"url":"https://reportstream.cdc.gov/fhir/StructureDefinition/hl7v2-date-time","valueString":"202102090000-0600"}]},"specimen":[{"reference":"Specimen/1712757038260290000.81c093a6-196b-4f10-bb3f-d021ed8f0016"},{"reference":"Specimen/1712757038257964000.0cea305a-356a-4793-9d84-003a4ea61b46"}],"result":[{"reference":"Observation/1712757038075149000.96fe7fb2-c4cd-4fb1-88a9-68ec17f1cacf"},{"reference":"Observation/1712757038079127000.21fda0ee-9592-44d4-915e-64e665f5d290"},{"reference":"Observation/1712757038081536000.cd121100-1cf4-4ded-a3c4-9642371aebec"},{"reference":"Observation/1712757038083984000.36967973-fe7a-4837-9774-a98bb93aa36d"}]}}]}"""
// The encoding ^~\&#! make this message not parseable
@Suppress("ktlint:standard:max-line-length")
private const val badEncodingHL7Record =
"""MSH|^~\&#!|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
// The missing | MSH^~\& make this message not parseable
@Suppress("ktlint:standard:max-line-length")
private const val unparseableHL7Record =
"""MSH^~\&|CDC PRIME - Atlanta, Georgia (Dekalb)^2.16.840.1.114222.4.1.237821^ISO|Avante at Ormond Beach^10D0876999^CLIA|PRIME_DOH|Prime ReportStream|20210210170737||ORU^R01^ORU_R01|371784|P|2.5.1|||NE|NE|USA||||PHLabReportNoAck^ELR_Receiver^2.16.840.1.113883.9.11^ISO
SFT|Centers for Disease Control and Prevention|0.1-SNAPSHOT|PRIME ReportStream|0.1-SNAPSHOT||20210210
PID|1||2a14112c-ece1-4f82-915c-7b3a8d152eda^^^Avante at Ormond Beach^PI||Buckridge^Kareem^Millie^^^^L||19580810|F||2106-3^White^HL70005^^^^2.5.1|688 Leighann Inlet^^South Rodneychester^TX^67071^^^^48077||7275555555:1:^PRN^^<EMAIL>^1^211^2240784|||||||||U^Unknown^HL70189||||||||N
ORC|RE|73a6e9bd-aaec-418e-813a-0ad33366ca85^6^7^8&F^9|73a6e9bd-aaec-418e-813a-0ad33366ca85|||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI||^WPN^^^1^386^6825220|20210209||||||Avante at Ormond Beach|170 North King Road^^Ormond Beach^FL^32174^^^^12127|^WPN^^<EMAIL>^1^407^7397506|^^^^32174
OBR|1|73a6e9bd-aaec-418e-813a-0ad33366ca85|0cba76f5-35e0-4a28-803a-2f31308aae9b|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN|||202102090000-0600|202102090000-0600||||||||1629082607^Eddin^Husam^^^^^^CMS&2.16.840.1.113883.3.249&ISO^^^^NPI|^WPN^^^1^386^6825220|||||202102090000-0600|||F
OBX|1|CWE|94558-4^SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay^LN||260415000^Not detected^SCT|||N^Normal (applies to non-numeric results)^HL70078|||F|||202102090000-0600|||CareStart COVID-19 Antigen test_Access Bio, Inc._EUA^^99ELR||202102090000-0600||||Avante at Ormond Beach^^^^^CLIA&2.16.840.1.113883.4.7&ISO^^^^10D0876999^CLIA|170 North King Road^^Ormond Beach^FL^32174^^^^12127
OBX|2|CWE|95418-0^Whether patient is employed in a healthcare setting^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|3|CWE|95417-2^First test for condition of interest^LN^^^^2.69||Y^Yes^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|4|CWE|95421-4^Resides in a congregate care setting^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
OBX|5|CWE|95419-8^Has symptoms related to condition of interest^LN^^^^2.69||N^No^HL70136||||||F|||202102090000-0600|||||||||||||||QST
SPM|1|0cba76f5-35e0-4a28-803a-2f31308aae9b||258500001^Nasopharyngeal swab^SCT||||71836000^Nasopharyngeal structure (body structure)^SCT^^^^2020-09-01|||||||||202102090000-0600|202102090000-0600"""
@Testcontainers
@ExtendWith(ReportStreamTestDatabaseSetupExtension::class)
class FhirFunctionIntegrationTests() {
@Container
val azuriteContainer = TestcontainersUtils.createAzuriteContainer(
customImageName = "azurite_fhirfunctionintegration1",
customEnv = mapOf(
"AZURITE_ACCOUNTS" to "devstoreaccount1:keydevstoreaccount1"
)
)
val oneOrganization = DeepOrganization(
"phd", "test", Organization.Jurisdiction.FEDERAL,
receivers = listOf(
Receiver(
"elr",
"phd",
Topic.TEST,
CustomerStatus.INACTIVE,
"one",
timing = Receiver.Timing(numberPerDay = 1, maxReportCount = 1, whenEmpty = Receiver.WhenEmpty())
),
Receiver(
"elr2",
"phd",
Topic.FULL_ELR,
CustomerStatus.ACTIVE,
"classpath:/metadata/hl7_mapping/ORU_R01/ORU_R01-base.yml",
timing = Receiver.Timing(numberPerDay = 1, maxReportCount = 1, whenEmpty = Receiver.WhenEmpty()),
jurisdictionalFilter = listOf("true"),
qualityFilter = listOf("true"),
processingModeFilter = listOf("true"),
format = Report.Format.HL7,
)
),
)
private fun makeWorkflowEngine(
metadata: Metadata,
settings: SettingsProvider,
databaseAccess: DatabaseAccess,
): WorkflowEngine {
return spyk(
WorkflowEngine.Builder().metadata(metadata).settingsProvider(settings).databaseAccess(databaseAccess)
.build()
)
}
private fun seedTask(
fileFormat: Report.Format,
currentAction: TaskAction,
nextAction: TaskAction,
nextEventAction: Event.EventAction,
topic: Topic,
taskIndex: Long = 0,
organization: DeepOrganization,
childReport: Report? = null,
bodyURL: String? = null,
): Report {
val report = Report(
fileFormat,
listOf(ClientSource(organization = organization.name, client = "Test Sender")),
1,
metadata = UnitTestUtils.simpleMetadata,
nextAction = nextAction,
topic = topic
)
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val action = Action().setActionName(currentAction)
val actionId = ReportStreamTestDatabaseContainer.testDatabaseAccess.insertAction(txn, action)
report.bodyURL = bodyURL ?: "http://${report.id}.${fileFormat.toString().lowercase()}"
val reportFile = ReportFile().setSchemaTopic(topic).setReportId(report.id)
.setActionId(actionId).setSchemaName("").setBodyFormat(fileFormat.toString()).setItemCount(1)
.setExternalName("test-external-name")
.setBodyUrl(report.bodyURL)
ReportStreamTestDatabaseContainer.testDatabaseAccess.insertReportFile(
reportFile, txn, action
)
if (childReport != null) {
ReportStreamTestDatabaseContainer.testDatabaseAccess
.insertReportLineage(
ReportLineage(
taskIndex,
actionId,
report.id,
childReport.id,
OffsetDateTime.now()
),
txn
)
}
ReportStreamTestDatabaseContainer.testDatabaseAccess.insertTask(
report,
fileFormat.toString().lowercase(),
report.bodyURL,
nextAction = ProcessEvent(
nextEventAction,
report.id,
Options.None,
emptyMap(),
emptyList()
),
txn
)
}
return report
}
@BeforeEach
fun beforeEach() {
clearAllMocks()
}
@AfterEach
fun afterEach() {
clearAllMocks()
}
@Test
fun `test does not update the DB or send messages on an error`() {
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirengine.azure.hl7_record.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} throws RuntimeException("manual error")
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\"" +
":\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirengine.azure.hl7_record.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
assertThrows<RuntimeException> {
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
}
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNull()
}
verify(exactly = 0) {
QueueAccess.sendMessage(any(), any())
}
}
@Test
fun `test successfully processes a convert message for HL7`() {
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirengine.azure.hl7_record.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirengine.azure.hl7_record.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNotNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNotNull()
}
verify(exactly = 1) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
}
@Test
fun `test successfully processes a convert message for bulk HL7 message`() {
val validBatch = cleanHL7Record + "\n" + invalidHL7Record
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns validBatch.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers { BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray()) }
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(validBatch.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(2)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(2)
}
verify(exactly = 2) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
}
verify(exactly = 1) {
BlobAccess.uploadBody(
Report.Format.FHIR,
match { bytes ->
val result = CompareData().compare(
bytes.inputStream(),
cleanHL7RecordConverted.byteInputStream(),
Report.Format.FHIR,
null
)
result.passed
},
any(), any(), any()
)
BlobAccess.uploadBody(
Report.Format.FHIR,
match { bytes ->
val result = CompareData().compare(
bytes.inputStream(),
invalidHL7RecordConverted.byteInputStream(),
Report.Format.FHIR,
null
)
result.passed
},
any(), any(), any()
)
}
}
@Test
fun `test no items routed for HL7 if any in batch are invalid`() {
val validBatch =
cleanHL7Record + "\n" + invalidHL7Record + "\n" + badEncodingHL7Record + "\n" + unparseableHL7Record
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns validBatch.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers { BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray()) }
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(validBatch.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val actionLogger = ActionLogger()
val fhirFunc = FHIRFunctions(
workflowEngine,
actionLogger = actionLogger,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(0)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(0)
assertThat(actionLogger.errors).hasSize(3)
}
verify(exactly = 0) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
}
@Test
fun `test successfully processes a convert message for a bulk (ndjson) FHIR message`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns bulkFhirRecord.toByteArray()
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} answers {
BlobAccess.BlobInfo(Report.Format.FHIR, UUID.randomUUID().toString(), "".toByteArray())
}
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val actionLogger = ActionLogger()
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(bulkFhirRecord.toByteArray()))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess,
actionLogger = actionLogger
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(Task.TASK)
assertThat(routeTask).hasSize(2)
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION.eq(TaskAction.route))
.fetchInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).hasSize(2)
// Expect two errors for the two badly formed bundles
assertThat(actionLogger.errors).hasSize(2)
}
verify(exactly = 2) {
QueueAccess.sendMessage(elrRoutingQueueName, any())
BlobAccess.uploadBody(Report.Format.FHIR, any(), any(), any(), any())
}
verify(exactly = 1) {
BlobAccess.uploadBody(
Report.Format.FHIR,
bulkFhirRecord.split("\n")[0].trim().toByteArray(),
any(),
any(),
any()
)
BlobAccess.uploadBody(
Report.Format.FHIR,
bulkFhirRecord.split("\n")[1].trim().toByteArray(),
any(),
any(),
any()
)
}
}
@Test
fun `test successfully processes a route message`() {
val reportServiceMock = mockk<ReportService>()
val report = seedTask(
Report.Format.HL7,
TaskAction.receive,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.FULL_ELR,
0,
oneOrganization
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
val routeFhirBytes =
File(VALID_FHIR_PATH).readBytes()
every {
BlobAccess.downloadBlobAsByteArray(any())
} returns routeFhirBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
every { reportServiceMock.getSenderName(any()) } returns "senderOrg.senderOrgClient"
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRRouter(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = reportServiceMock
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"route\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.hl7\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(routeFhirBytes))}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doRoute(queueMessage, 1, fhirEngine, actionHistory)
val convertTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(convertTask.routedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val routeTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.translate))
.fetchOneInto(Task.TASK)
assertThat(routeTask).isNotNull()
val convertReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.NEXT_ACTION
.eq(TaskAction.translate)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(convertReportFile).isNotNull()
}
verify(exactly = 1) {
QueueAccess.sendMessage(elrTranslationQueueName, any())
}
}
/*
Send a FHIR message to an HL7v2 receiver and ensure the message receiver receives is translated to HL7v2
*/
@Test
fun `test successfully processes a translate message when isSendOriginal is false`() {
// set up and seed azure blobstore
val blobConnectionString =
"""DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=keydevstoreaccount1;BlobEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10000
)
}/devstoreaccount1;QueueEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10001
)
}/devstoreaccount1;"""
val blobContainerMetadata = BlobAccess.BlobContainerMetadata(
"container1",
blobConnectionString
)
mockkObject(BlobAccess)
every { BlobAccess getProperty "defaultBlobMetadata" } returns blobContainerMetadata
// upload reports
val receiveBlobName = "receiveBlobName"
val translateFhirBytes = File(
MULTIPLE_TARGETS_FHIR_PATH
).readBytes()
val receiveBlobUrl = BlobAccess.uploadBlob(
receiveBlobName,
translateFhirBytes,
blobContainerMetadata
)
// Seed the steps backwards so report lineage can be correctly generated
val translateReport = seedTask(
Report.Format.FHIR,
TaskAction.translate,
TaskAction.send,
Event.EventAction.SEND,
Topic.ELR_ELIMS,
100,
oneOrganization
)
val routeReport = seedTask(
Report.Format.FHIR,
TaskAction.route,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.ELR_ELIMS,
99,
oneOrganization,
translateReport
)
val convertReport = seedTask(
Report.Format.FHIR,
TaskAction.convert,
TaskAction.route,
Event.EventAction.ROUTE,
Topic.ELR_ELIMS,
98,
oneOrganization,
routeReport
)
val receiveReport = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.ELR_ELIMS,
97,
oneOrganization,
convertReport,
receiveBlobUrl
)
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = spyk(
FHIRTranslator(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = ReportService(ReportGraph(ReportStreamTestDatabaseContainer.testDatabaseAccess))
)
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { QueueAccess.sendMessage(any(), any()) } returns Unit
mockkObject(BlobAccess.BlobContainerMetadata)
every { BlobAccess.BlobContainerMetadata.build("metadata", any()) } returns BlobAccess.BlobContainerMetadata(
"metadata",
blobConnectionString
)
// The topic param of queueMessage is what should determine how the Translate function runs
val queueMessage = "{\"type\":\"translate\",\"reportId\":\"${translateReport.id}\"," +
"\"blobURL\":\"" + receiveBlobUrl +
"\",\"digest\":\"${
BlobAccess.digestToString(
BlobAccess.sha256Digest(
translateFhirBytes
)
)
}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"," +
"\"receiverFullName\":\"phd.elr2\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doTranslate(queueMessage, 1, fhirEngine, actionHistory)
// verify task and report_file tables were updated correctly in the Translate function (new task and new
// record file created)
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val queueTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.batch))
.fetchOneInto(Task.TASK)
assertThat(queueTask).isNotNull()
val sendReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.REPORT_ID
.eq(queueTask!!.reportId)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(sendReportFile).isNotNull()
// verify sendReportFile message does not match the original message from receive step
assertThat(BlobAccess.downloadBlobAsByteArray(sendReportFile!!.bodyUrl, blobContainerMetadata))
.isNotEqualTo(BlobAccess.downloadBlobAsByteArray(receiveReport.bodyURL, blobContainerMetadata))
}
// verify we did not call the sendOriginal function
verify(exactly = 0) {
fhirEngine.sendOriginal(any(), any(), any())
}
// verify we called the sendTranslated function
verify(exactly = 1) {
fhirEngine.sendTranslated(any(), any(), any())
}
// verify sendMessage did not get called because next action should be Batch
verify(exactly = 0) {
QueueAccess.sendMessage(any(), any())
}
}
/*
Send a FHIR message to an HL7v2 receiver and ensure the message receiver receives is the original FHIR and NOT
translated to HL7v2
*/
@Test
fun `test successfully processes a translate message when isSendOriginal is true`() {
// set up and seed azure blobstore
val blobConnectionString =
"""DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=keydevstoreaccount1;BlobEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10000
)
}/devstoreaccount1;QueueEndpoint=http://${azuriteContainer.host}:${
azuriteContainer.getMappedPort(
10001
)
}/devstoreaccount1;"""
val blobContainerMetadata = BlobAccess.BlobContainerMetadata(
"container1",
blobConnectionString
)
mockkObject(BlobAccess)
every { BlobAccess getProperty "defaultBlobMetadata" } returns blobContainerMetadata
// upload reports
val receiveBlobName = "receiveBlobName"
val translateFhirBytes = File(
MULTIPLE_TARGETS_FHIR_PATH
).readBytes()
val receiveBlobUrl = BlobAccess.uploadBlob(
receiveBlobName,
translateFhirBytes,
blobContainerMetadata
)
// Seed the steps backwards so report lineage can be correctly generated
val translateReport = seedTask(
Report.Format.FHIR,
TaskAction.translate,
TaskAction.send,
Event.EventAction.SEND,
Topic.ELR_ELIMS,
100,
oneOrganization
)
val routeReport = seedTask(
Report.Format.FHIR,
TaskAction.route,
TaskAction.translate,
Event.EventAction.TRANSLATE,
Topic.ELR_ELIMS,
99,
oneOrganization,
translateReport
)
val convertReport = seedTask(
Report.Format.FHIR,
TaskAction.convert,
TaskAction.route,
Event.EventAction.ROUTE,
Topic.ELR_ELIMS,
98,
oneOrganization,
routeReport
)
val receiveReport = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.ELR_ELIMS,
97,
oneOrganization,
convertReport,
receiveBlobUrl
)
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = spyk(
FHIRTranslator(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
reportService = ReportService(ReportGraph(ReportStreamTestDatabaseContainer.testDatabaseAccess))
)
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
UnitTestUtils.simpleMetadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { QueueAccess.sendMessage(any(), any()) } returns Unit
// The topic param of queueMessage is what should determine how the Translate function runs
val queueMessage = "{\"type\":\"translate\",\"reportId\":\"${translateReport.id}\"," +
"\"blobURL\":\"" + receiveBlobUrl +
"\",\"digest\":\"${
BlobAccess.digestToString(
BlobAccess.sha256Digest(
translateFhirBytes
)
)
}\",\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"elr-elims\"," +
"\"receiverFullName\":\"phd.elr2\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doTranslate(queueMessage, 1, fhirEngine, actionHistory)
// verify task and report_file tables were updated correctly in the Translate function
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val sendTask = DSL.using(txn).select(Task.TASK.asterisk()).from(Task.TASK)
.where(Task.TASK.NEXT_ACTION.eq(TaskAction.send))
.fetchOneInto(Task.TASK)
assertThat(sendTask).isNotNull()
val sendReportFile =
DSL.using(txn).select(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.asterisk())
.from(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
.where(
gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE.REPORT_ID
.eq(sendTask!!.reportId)
)
.fetchOneInto(gov.cdc.prime.router.azure.db.tables.ReportFile.REPORT_FILE)
assertThat(sendReportFile).isNotNull()
// verify sendReportFile message matches the original message from receive step
assertThat(BlobAccess.downloadBlobAsByteArray(sendReportFile!!.bodyUrl, blobContainerMetadata))
.isEqualTo(BlobAccess.downloadBlobAsByteArray(receiveReport.bodyURL, blobContainerMetadata))
}
// verify we called the sendOriginal function
verify(exactly = 1) {
fhirEngine.sendOriginal(any(), any(), any())
}
// verify we did not call the sendTranslated function
verify(exactly = 0) {
fhirEngine.sendTranslated(any(), any(), any())
}
// verify sendMessage did get called because next action should be Send since isOriginal skips the batch
// step
verify(exactly = 1) {
QueueAccess.sendMessage(any(), any())
}
}
@Test
fun `test unmapped observation error messages`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
val fhirRecordBytes = fhirengine.azure.fhirRecord.toByteArray()
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirRecordBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirRecordBytes))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val actionLogs = DSL.using(txn)
.select(ActionLog.ACTION_LOG.asterisk())
.from(ActionLog.ACTION_LOG)
.fetchMany()
.map { it.into(gov.cdc.prime.router.azure.db.tables.pojos.ActionLog::class.java) }
assertThat(actionLogs.size).isEqualTo(1)
assertThat(actionLogs[0].size).isEqualTo(2)
assertThat(actionLogs[0].map { it.detail.message }).isEqualTo(
listOf(
"Missing mapping for code(s): 80382-5",
"Missing mapping for code(s): 260373001"
)
)
}
}
@Test
fun `test codeless observation error message`() {
val report = seedTask(
Report.Format.FHIR,
TaskAction.receive,
TaskAction.convert,
Event.EventAction.CONVERT,
Topic.FULL_ELR,
0,
oneOrganization
)
val metadata = Metadata(UnitTestUtils.simpleSchema)
val fhirRecordBytes = fhirengine.azure.codelessFhirRecord.toByteArray()
metadata.lookupTableStore += mapOf(
"observation-mapping" to LookupTable("observation-mapping", emptyList())
)
mockkObject(BlobAccess)
mockkObject(QueueMessage)
mockkObject(QueueAccess)
every { BlobAccess.downloadBlobAsByteArray(any()) } returns fhirRecordBytes
every {
BlobAccess.uploadBody(
any(),
any(),
any(),
any(),
any()
)
} returns BlobAccess.BlobInfo(Report.Format.FHIR, "", "".toByteArray())
every { QueueAccess.sendMessage(any(), any()) } returns Unit
val settings = FileSettings().loadOrganizations(oneOrganization)
val fhirEngine = FHIRConverter(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess,
)
val actionHistory = spyk(ActionHistory(TaskAction.receive))
val workflowEngine =
makeWorkflowEngine(
metadata,
settings,
ReportStreamTestDatabaseContainer.testDatabaseAccess
)
val queueMessage = "{\"type\":\"convert\",\"reportId\":\"${report.id}\"," +
"\"blobURL\":\"http://azurite:10000/devstoreaccount1/reports/receive%2Fignore.ignore-full-elr%2F" +
"None-${report.id}.fhir\",\"digest\":" +
"\"${BlobAccess.digestToString(BlobAccess.sha256Digest(fhirRecordBytes))}\"," +
"\"blobSubFolderName\":" +
"\"ignore.ignore-full-elr\",\"schemaName\":\"\",\"topic\":\"full-elr\"}"
val fhirFunc = FHIRFunctions(
workflowEngine,
databaseAccess = ReportStreamTestDatabaseContainer.testDatabaseAccess
)
fhirFunc.doConvert(queueMessage, 1, fhirEngine, actionHistory)
val processTask = ReportStreamTestDatabaseContainer.testDatabaseAccess.fetchTask(report.id)
assertThat(processTask.processedAt).isNotNull()
ReportStreamTestDatabaseContainer.testDatabaseAccess.transact { txn ->
val actionLogs = DSL.using(txn)
.select(ActionLog.ACTION_LOG.asterisk())
.from(ActionLog.ACTION_LOG).fetchMany()
.map { it.into(gov.cdc.prime.router.azure.db.tables.pojos.ActionLog::class.java) }
assertThat(actionLogs.size).isEqualTo(1)
assertThat(actionLogs[0].size).isEqualTo(1)
assertThat(actionLogs[0][0].detail.message).isEqualTo("Observation missing code")
}
}
}
| 1,389 |
Kotlin
|
39
| 64 |
ecd862e53ce7fd971deea6fd100fa6b3ea49e171
| 135,485 |
prime-reportstream
|
Creative Commons Zero v1.0 Universal
|
pulsar/messaging/adapter/src/main/kotlin/org/sollecitom/chassis/pulsar/messaging/adapter/MessageContextPropertiesSerde.kt
|
sollecitom
| 669,483,842 | false |
{"Kotlin": 868904, "Java": 30834}
|
package org.sollecitom.chassis.pulsar.messaging.adapter
import org.sollecitom.chassis.messaging.domain.Message
internal object MessageContextPropertiesSerde {
private val parentMessageIdProperty = ProtocolProperties.contextualize("MESSAGE-CONTEXT-PARENT-MESSAGE-ID")
private val originatingMessageIdProperty = ProtocolProperties.contextualize("MESSAGE-CONTEXT-ORIGINATING-MESSAGE-ID")
fun serialize(context: Message.Context): Map<String, String> = buildMap {
context.parentMessageId?.let {
put(parentMessageIdProperty, MessageIdStringSerde.serialize(it))
}
context.originatingMessageId?.let {
put(originatingMessageIdProperty, MessageIdStringSerde.serialize(it))
}
}
fun deserialize(properties: Map<String, String>): Message.Context {
val parentMessageId = properties[parentMessageIdProperty]?.let(MessageIdStringSerde::deserialize)
val originatingMessageId = properties[originatingMessageIdProperty]?.let(MessageIdStringSerde::deserialize)
return Message.Context(parentMessageId = parentMessageId, originatingMessageId = originatingMessageId)
}
}
| 0 |
Kotlin
|
0
| 2 |
d11bf12bc66105bbf7edd35d01fbbadc200c3ee8
| 1,158 |
chassis
|
MIT License
|
compiler/testData/codegen/box/inlineClasses/returnResult/classGenericOverride.kt
|
JetBrains
| 3,432,266 | false | null |
// WITH_RUNTIME
// KJS_WITH_FULL_RUNTIME
interface I<T> {
fun foo(): T
}
class C : I<Result<String>> {
override fun foo(): Result<String> = Result.success("OK")
}
fun box(): String {
if (((C() as I<Result<String>>).foo() as Result<String>).getOrThrow() != "OK") return "FAIL 1"
return C().foo().getOrThrow()
}
| 181 | null |
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 329 |
kotlin
|
Apache License 2.0
|
ui/features/quick-note/src/main/java/com/example/quick_note/QuickActivity.kt
|
City-Zouitel
| 576,223,915 | false | null |
package com.example.quick_note
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import com.example.datastore.DataStore
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class QuickActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppTheme {
Quick() {
finish()
}
}
}
}
@Composable
private fun AppTheme(content: @Composable () -> Unit) {
val currentTheme = DataStore(LocalContext.current).isDarkTheme.collectAsState(false).value
val systemUiController = rememberSystemUiController()
val isDarkUi = isSystemInDarkTheme()
val theme = when {
isSystemInDarkTheme() -> darkColorScheme()
currentTheme -> darkColorScheme()
else -> lightColorScheme()
}
SideEffect {
systemUiController.apply {
setStatusBarColor(Color.Transparent, !isDarkUi)
setNavigationBarColor(
if (currentTheme || isDarkUi) Color(red = 28, green = 27, blue = 31)
else Color(red = 255, green = 251, blue = 254)
)
}
}
MaterialTheme(colorScheme = theme, content = content)
}
}
| 18 |
Kotlin
|
4
| 25 |
8b9da426250b75670832d170ee9d77c793b9881e
| 1,973 |
JetNote
|
Apache License 2.0
|
app/src/main/java/com/example/android/marsphotos/overview/FruitsAdapter.kt
|
kr-end
| 721,152,070 | false |
{"Kotlin": 7595}
|
package com.example.android.marsphotos.overview
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.marsphotos.databinding.GridViewItemBinding
import com.example.android.marsphotos.network.model.Fruit
class FruitsAdapter :
ListAdapter<Fruit, FruitsAdapter.FruitTextViewHolder>(DiffCallback) {
class FruitTextViewHolder(private val binding: GridViewItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(fruit: Fruit) {
val nutrition = fruit.nutritions
val fruta = buildString {
append("${fruit.name}\n")
append("Id: ${fruit.id}\n")
append("Family: ${fruit.family}\n")
append("Order: ${fruit.order}\n")
append("Genus: ${fruit.genus}\n")
append("Calories: ${nutrition.calories}\n")
append("Fat: ${nutrition.fat}\n")
append("Sugar: ${nutrition.sugar}\n")
append("Carbohydrates: ${nutrition.carbohydrates}\n")
append("Protein: ${nutrition.protein}\n")
}
binding.fruitTxt.text = fruta
binding.executePendingBindings()
}
}
companion object DiffCallback : DiffUtil.ItemCallback<Fruit>() {
override fun areItemsTheSame(oldItem: Fruit, newItem: Fruit): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: Fruit, newItem: Fruit): Boolean {
return oldItem.name == newItem.name
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): FruitTextViewHolder {
return FruitTextViewHolder(
GridViewItemBinding.inflate(LayoutInflater.from(parent.context))
)
}
/**
* Replaces the contents of a view (invoked by the layout manager)
*/
override fun onBindViewHolder(holder: FruitTextViewHolder, position: Int) {
val fruit = getItem(position)
holder.bind(fruit)
}
}
| 0 |
Kotlin
|
0
| 0 |
7ce5e7e2aec4f5ed1bae3ffe3c3b6e8bd74d44b6
| 2,205 |
ServicioFrutas_1
|
Apache License 2.0
|
frameanimation/src/main/java/com/yuyashuai/frameanimation/io/BitmapPool.kt
|
yuyashuai
| 74,862,716 | false | null |
package com.yuyashuai.frameanimation.io
import android.graphics.Bitmap
import com.yuyashuai.frameanimation.repeatmode.RepeatStrategy
/**
* @author yuyashuai 2019-04-24.
* a pool store and reuse the bitmaps resident in memory
*/
interface BitmapPool {
/**
* take an bitmap from the pool
* don't allocate objects here
* @return null a animation stop signal
*/
@Throws(InterruptedException::class)
fun take(): Bitmap?
/**
* Start running,
* @param repeatStrategy bitmap order
*/
fun start(repeatStrategy: RepeatStrategy, index: Int)
/**
* recycler the bitmap for reuse
*/
fun recycle(bitmap: Bitmap)
/**
* stop decode bitmap
*/
fun stop()
/**
* release all resources, like thread, bitmap...
*/
fun release()
/**
* used for animation listener
*/
fun getRepeatStrategy(): RepeatStrategy?
}
| 10 |
Kotlin
|
45
| 296 |
a076d9c34a971b01b91b708c4c4900ae732b1c87
| 924 |
FrameAnimation
|
Apache License 2.0
|
src/dev/lunarcoffee/blazelight/model/internal/users/im/IMDataList.kt
|
lunarcoffee
| 214,299,039 | false |
{"Kotlin": 166835, "CSS": 18966, "JavaScript": 1102}
|
package dev.lunarcoffee.blazelight.model.internal.users.im
import dev.lunarcoffee.blazelight.model.internal.std.Dateable
import dev.lunarcoffee.blazelight.model.internal.std.Identifiable
typealias IUserIMDataList = IMDataList<UserIMData, UserIMMessage>
// [IMDataList]s store a list of a [IMData] that store message history.
interface IMDataList<T : IMData<V>, V : IMMessage> : Dateable, Identifiable {
val data: MutableList<T>
val userId: Long
fun getByDataId(dataId: Long): T?
fun addByDataId(dataId: Long, message: V)
}
| 0 |
Kotlin
|
0
| 1 |
3f0a227fe8d48cbeece5d677e8e36974d00e4e9c
| 543 |
Blazelight
|
MIT License
|
composeApp/src/androidMain/kotlin/com/calvin/box/movie/player/exo/MediaSourceFactory.kt
|
lhzheng880828
| 834,021,637 | false |
{"Kotlin": 902589, "Java": 712396, "JavaScript": 198922, "Shell": 3042, "Ruby": 2141, "Batchfile": 1261, "Swift": 1155, "HTML": 334, "CSS": 102}
|
package com.calvin.box.movie.player.exo
import android.content.Context
import android.net.Uri
import androidx.annotation.OptIn
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.HttpDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.exoplayer.drm.DrmSessionManagerProvider
import androidx.media3.exoplayer.source.ConcatenatingMediaSource2
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy
import androidx.media3.extractor.DefaultExtractorsFactory
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactory
import androidx.media3.extractor.ts.TsExtractor
import com.calvin.box.movie.ContextProvider
import com.calvin.box.movie.getPlatform
import okhttp3.OkHttpClient
@UnstableApi
class MediaSourceFactory @OptIn(markerClass = [UnstableApi::class]) constructor() :
MediaSource.Factory {
/* private val defaultMediaSourceFactory: DefaultMediaSourceFactory
private var httpDataSourceFactory: HttpDataSource.Factory? = null
get() {
if (field == null) field = DefaultDataSource.Factory(OkHttp.client())
return field
}
private var dataSourceFactory: DataSource.Factory? = null
get() {
if (field == null) field = buildReadOnlyCacheDataSource(
DefaultDataSource.Factory(
(ContextProvider.context as Context),
httpDataSourceFactory!!
)
)
return field
}
private var extractorsFactory: ExtractorsFactory? = null
get() {
if (field == null) field =
DefaultExtractorsFactory().setTsExtractorFlags(DefaultTsPayloadReaderFactory.FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS)
.setTsExtractorTimestampSearchBytes(TsExtractor.DEFAULT_TIMESTAMP_SEARCH_BYTES * 3)
return field
}
init {
defaultMediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory, extractorsFactory)
}*/
private val defaultMediaSourceFactory: DefaultMediaSourceFactory by lazy {
DefaultMediaSourceFactory(dataSourceFactory, extractorsFactory)
}
private val httpDataSourceFactory: HttpDataSource.Factory by lazy {
val okhttpClient = getPlatform().getHostOkhttp() as OkHttpClient
OkHttpDataSource.Factory(okhttpClient)
}
private val dataSourceFactory: DataSource.Factory by lazy {
buildReadOnlyCacheDataSource(
DefaultDataSource.Factory(
(ContextProvider.context as Context),
httpDataSourceFactory
)
)
}
private val extractorsFactory: ExtractorsFactory by lazy {
DefaultExtractorsFactory()
.setTsExtractorFlags(DefaultTsPayloadReaderFactory.FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS)
.setTsExtractorTimestampSearchBytes(TsExtractor.DEFAULT_TIMESTAMP_SEARCH_BYTES * 3)
}
override fun setDrmSessionManagerProvider(drmSessionManagerProvider: DrmSessionManagerProvider): MediaSource.Factory {
return defaultMediaSourceFactory.setDrmSessionManagerProvider(drmSessionManagerProvider)
}
override fun setLoadErrorHandlingPolicy(loadErrorHandlingPolicy: LoadErrorHandlingPolicy): MediaSource.Factory {
return defaultMediaSourceFactory.setLoadErrorHandlingPolicy(loadErrorHandlingPolicy)
}
override fun getSupportedTypes(): IntArray {
return defaultMediaSourceFactory.supportedTypes
}
override fun createMediaSource(mediaItem: MediaItem): MediaSource {
return if (mediaItem.mediaId.contains("***") && mediaItem.mediaId.contains("|||")) {
createConcatenatingMediaSource(setHeader(mediaItem))
} else {
defaultMediaSourceFactory.createMediaSource(setHeader(mediaItem))
}
}
private fun setHeader(mediaItem: MediaItem): MediaItem {
val headers: MutableMap<String, String> = HashMap()
for (key in mediaItem.requestMetadata.extras!!.keySet()) headers[key] =
mediaItem.requestMetadata.extras!![key].toString()
httpDataSourceFactory.setDefaultRequestProperties(headers)
return mediaItem
}
private fun createConcatenatingMediaSource(mediaItem: MediaItem): MediaSource {
val builder: ConcatenatingMediaSource2.Builder = ConcatenatingMediaSource2.Builder()
for (split in mediaItem.mediaId.split("\\*\\*\\*".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()) {
val info =
split.split("\\|\\|\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (info.size >= 2) builder.add(
defaultMediaSourceFactory.createMediaSource(
mediaItem.buildUpon().setUri(
Uri.parse(
info[0]
)
).build()
), info[1].toLong()
)
}
return builder.build()
}
private fun buildReadOnlyCacheDataSource(upstreamFactory: DataSource.Factory): CacheDataSource.Factory {
return CacheDataSource.Factory().setCache(CacheManager.get().getCache())
.setUpstreamDataSourceFactory(upstreamFactory).setCacheWriteDataSinkFactory(null)
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
}
}
| 0 |
Kotlin
|
0
| 1 |
2bb12d7dea2a9abd74e161efbef5d0cc006846ed
| 5,733 |
MovieBox
|
Apache License 2.0
|
data/library/implementation/src/commonMain/kotlin/com/thomaskioko/tvmaniac/watchlist/implementation/LibraryDaoImpl.kt
|
thomaskioko
| 361,393,353 | false |
{"Kotlin": 560203, "Swift": 94284}
|
package com.thomaskioko.tvmaniac.watchlist.implementation
import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import com.thomaskioko.tvmaniac.core.db.TvManiacDatabase
import com.thomaskioko.tvmaniac.core.db.WatchedShow
import com.thomaskioko.tvmaniac.core.db.Watchlist
import com.thomaskioko.tvmaniac.db.Id
import com.thomaskioko.tvmaniac.shows.api.WatchlistDao
import com.thomaskioko.tvmaniac.util.model.AppCoroutineDispatchers
import kotlinx.coroutines.flow.Flow
import me.tatarka.inject.annotations.Inject
@Inject
class WatchlistDaoImpl(
private val database: TvManiacDatabase,
private val dispatchers: AppCoroutineDispatchers,
) : WatchlistDao {
override fun upsert(watchlist: Watchlist) {
database.transaction {
database.watchlistQueries.insertOrReplace(
id = watchlist.id,
synced = watchlist.synced,
created_at = watchlist.created_at,
)
}
}
override fun upsert(watchedShowList: List<Watchlist>) {
watchedShowList.forEach { upsert(it) }
}
override fun getWatchedShows(): List<WatchedShow> =
database.watchlistQueries.watchedShow()
.executeAsList()
override fun observeWatchedShows(): Flow<List<WatchedShow>> =
database.watchlistQueries.watchedShow()
.asFlow()
.mapToList(dispatchers.io)
override fun getUnSyncedShows(): List<Watchlist> =
database.watchlistQueries.unsyncedShows()
.executeAsList()
override fun updateShowSyncState(traktId: Long) {
database.watchlistQueries.updateFollowedState(
id = Id(traktId),
synced = true,
)
}
override fun removeShow(traktId: Long) {
database.watchlistQueries.removeShowFromWatchlist(Id(traktId))
}
}
| 9 |
Kotlin
|
16
| 136 |
625b1bbab9aba4e5031778ba5020639106d4b4e9
| 1,862 |
tv-maniac
|
Apache License 2.0
|
codes/LocalFunctions.kt
|
iammert
| 172,658,295 | false | null |
/*
Local functions are good for code reuse,
just be careful not to overuse them to avoid confusion.
*/
fun foo(a: Int) {
fun local(b: Int) {
return a + b
}
return local(1)
}
| 1 | null |
1
| 8 |
f89479a5b25b6ec0bd26113d316d16e46bb30771
| 178 |
android-daily-tips-1
|
MIT License
|
src/jsMain/kotlin/com/jeffpdavidson/kotwords/web/SpiralForm.kt
|
jpd236
| 143,651,464 | false | null |
package com.jeffpdavidson.kotwords.web
import com.jeffpdavidson.kotwords.KotwordsInternal
import com.jeffpdavidson.kotwords.model.Puzzle
import com.jeffpdavidson.kotwords.model.Spiral
import com.jeffpdavidson.kotwords.util.trimmedLines
import com.jeffpdavidson.kotwords.web.html.FormFields
import com.jeffpdavidson.kotwords.web.html.Html
@JsExport
@KotwordsInternal
class SpiralForm {
private val form = PuzzleFileForm("spiral", ::createPuzzle)
private val inwardAnswers: FormFields.TextBoxField = FormFields.TextBoxField("inward-answers")
private val inwardClues: FormFields.TextBoxField = FormFields.TextBoxField("inward-clues")
private val outwardAnswers: FormFields.TextBoxField = FormFields.TextBoxField("outward-answers")
private val outwardClues: FormFields.TextBoxField = FormFields.TextBoxField("outward-clues")
private val inwardCells: FormFields.TextBoxField = FormFields.TextBoxField("inward-cells")
init {
Html.renderPage {
form.render(this, bodyBlock = {
inwardAnswers.render(this, "Inward answers") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
inwardClues.render(this, "Inward clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
outwardAnswers.render(this, "Outward answers") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
outwardClues.render(this, "Outward clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
inwardCells.render(this, "Inward cells (optional)") {
placeholder = "Each cell of the spiral, in sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored. " +
"Defaults to each letter of the inward answers. " +
"May be used to place more than one letter in some or all cells, " +
"e.g. for a Crushword Spiral."
rows = "5"
}
})
}
}
private suspend fun createPuzzle(): Puzzle {
val spiral = Spiral(
title = form.title,
creator = form.creator,
copyright = form.copyright,
description = form.description,
inwardAnswers = inwardAnswers.value.uppercase().split("\\s+".toRegex()),
inwardClues = inwardClues.value.trimmedLines(),
outwardAnswers = outwardAnswers.value.uppercase().split("\\s+".toRegex()),
outwardClues = outwardClues.value.trimmedLines(),
inwardCellsInput = if (inwardCells.value.isBlank()) {
listOf()
} else {
inwardCells.value.uppercase().split("\\s+".toRegex())
},
)
return spiral.asPuzzle()
}
}
| 7 |
Kotlin
|
2
| 12 |
28a3940e6268118be5496f8d21ce0e965f8641da
| 3,266 |
kotwords
|
Apache License 2.0
|
app/src/main/java/com/repository/androidrepository/data/remote/RepositoryService.kt
|
Imranseu17
| 505,557,379 | false |
{"Kotlin": 45642, "Java": 8779}
|
package com.repository.androidrepository.data.remote
import com.repository.androidrepository.models.Root
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Query
interface RepositoryService {
@Headers( "Content-Type: application/json; charset=utf-8" )
@GET("repositories")
suspend fun getAllRepositorys(@Query("q") keyword:String,
@Query("sort") sort:String)
:Response<Root>
}
| 0 |
Kotlin
|
0
| 1 |
89544d213b706765fd3f28eb620fe2bffafd2501
| 481 |
GitRepoAndroid
|
Apache License 2.0
|
decompose/src/commonMain/kotlin/com/arkivanov/decompose/router/slot/ValueExt.kt
|
arkivanov
| 437,015,897 | false |
{"Kotlin": 700677}
|
package com.arkivanov.decompose.router.slot
import com.arkivanov.decompose.Child
import com.arkivanov.decompose.value.Value
val <C : Any, T : Any> Value<ChildSlot<C, T>>.child: Child.Created<C, T>? get() = value.child
| 2 |
Kotlin
|
84
| 2,207 |
8af551e8895951a5082a5d2750335713d673f80b
| 220 |
Decompose
|
Apache License 2.0
|
content-types/content-types-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/org/orkg/contenttypes/adapter/output/neo4j/internal/LabelsAndClasses.kt
|
TIBHannover
| 197,416,205 | false |
{"Kotlin": 2966676, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package org.orkg.contenttypes.adapter.output.neo4j.internal
import org.orkg.contenttypes.output.LabelAndClassService
import org.springframework.stereotype.Component
@Component
class LabelsAndClasses : LabelAndClassService {
override val benchmarkClass: String = BENCHMARK_CLASS
override val benchmarkPredicate: String = BENCHMARK_PREDICATE
override val datasetClass: String = DATASET_CLASS
override val datasetPredicate: String = DATASET_PREDICATE
override val sourceCodePredicate: String = SOURCE_CODE_PREDICATE
override val modelClass: String = MODEL_CLASS
override val modelPredicate: String = MODEL_PREDICATE
override val quantityClass: String = QUANTITY_CLASS
override val quantityPredicate: String = QUANTITY_PREDICATE
override val metricClass: String = QUANTITY_KIND_CLASS
override val metricPredicate: String = QUANTITY_KIND_PREDICATE
override val quantityValueClass: String = QUANTITY_VALUE_CLASS
override val quantityValuePredicate: String =
QUANTITY_VALUE_PREDICATE
override val numericValuePredicate: String =
NUMERIC_VALUE_PREDICATE
}
| 0 |
Kotlin
|
1
| 5 |
f9de52bdf498fdc200e7f655a52cecff215c1949
| 1,122 |
orkg-backend
|
MIT License
|
paymentsheet/src/main/java/com/stripe/android/paymentsheet/ui/Accessibility.kt
|
stripe
| 6,926,049 | false |
{"Kotlin": 13814299, "Java": 102588, "Ruby": 45779, "HTML": 42045, "Shell": 23905, "Python": 21891}
|
package com.stripe.android.paymentsheet.ui
internal fun String.readNumbersAsIndividualDigits(): String {
// This makes the screen reader read out numbers digit by digit
// one one one one vs one thousand one hundred eleven
return replace("\\d".toRegex(), "$0 ")
}
| 88 |
Kotlin
|
644
| 1,277 |
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
| 277 |
stripe-android
|
MIT License
|
app/src/main/java/com/vincent/recipe_mvvm_jetpack/presentation/components/util/SnackbarController.kt
|
VincentGaoHJ
| 398,203,841 | false | null |
package com.vincent.recipe_mvvm_jetpack.presentation.components.util
import androidx.compose.material.ScaffoldState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class SnackbarController(
private val scope: CoroutineScope
) {
private var snackbarJob: Job? = null
// When this is recreated cause by some wired reason, it should be starting with a clean state
init {
cancelActiveJob()
}
fun getScope() = scope
fun showSnackbar(
scaffoldState: ScaffoldState,
message: String,
actionLabel: String,
) {
if (snackbarJob == null) {
snackbarJob = scope.launch {
scaffoldState.snackbarHostState.showSnackbar(
message = message,
actionLabel = actionLabel
)
cancelActiveJob()
}
} else {
cancelActiveJob()
snackbarJob = scope.launch {
scaffoldState.snackbarHostState.showSnackbar(
message = message,
actionLabel = actionLabel
)
cancelActiveJob()
}
}
}
private fun cancelActiveJob() {
snackbarJob?.let { job ->
job.cancel()
snackbarJob = Job()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
a5ccee3774b5077bf715bf798ee52c8e7271d633
| 1,376 |
Recipe-MVVM-Jetpack
|
MIT License
|
app/src/main/java/co/gov/isabu/showcase/activities/ErrorActivity.kt
|
AzaelDragon
| 216,564,766 | false | null |
package co.gov.isabu.showcase.activities
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import co.gov.isabu.showcase.R
class ErrorActivity : AppCompatActivity() {
/**
* Create a new activity and assign a simple button switcher to a new activity.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_error)
val button = findViewById<Button>(R.id.error_button)
button.setOnClickListener {
val intent = Intent(this, SplashActivity::class.java)
startActivity(intent)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
30253e5cc75f06c43329316e2f0892022d5aacb2
| 721 |
isabu-showcase-app
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/TaskResume.kt
|
Danilo-Araujo-Silva
| 271,904,885 | false | null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: TaskResume
*
* Full name: System`TaskResume
*
* Usage: TaskResume[task] resumes execution of the specified task.
*
* Options: None
*
* Listable
* Attributes: Protected
*
* local: paclet:ref/TaskResume
* Documentation: web: http://reference.wolfram.com/language/ref/TaskResume.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun taskResume(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("TaskResume", arguments.toMutableList(), options)
}
| 2 |
Kotlin
|
0
| 3 |
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 970 |
mathemagika
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/CameraViewfinder.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.CameraViewfinder: ImageVector
get() {
if (_cameraViewfinder != null) {
return _cameraViewfinder!!
}
_cameraViewfinder = Builder(name = "CameraViewfinder", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(8.0f, 22.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-1.0f)
curveToRelative(-3.032f, 0.0f, -5.5f, -2.468f, -5.5f, -5.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 1.379f, 1.121f, 2.5f, 2.5f, 2.5f)
horizontalLineToRelative(1.0f)
curveToRelative(0.828f, 0.0f, 1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(22.5f, 16.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 1.379f, -1.121f, 2.5f, -2.5f, 2.5f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
horizontalLineToRelative(1.0f)
curveToRelative(3.032f, 0.0f, 5.5f, -2.468f, 5.5f, -5.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(18.5f, 0.0f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
horizontalLineToRelative(1.0f)
curveToRelative(1.379f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -3.032f, -2.468f, -5.5f, -5.5f, -5.5f)
close()
moveTo(1.5f, 8.0f)
curveToRelative(0.828f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.379f, 1.121f, -2.5f, 2.5f, -2.5f)
horizontalLineToRelative(1.0f)
curveToRelative(0.828f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
horizontalLineToRelative(-1.0f)
curveTo(2.468f, 0.0f, 0.0f, 2.468f, 0.0f, 5.5f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
close()
moveTo(12.0f, 10.0f)
curveToRelative(-1.105f, 0.0f, -2.0f, 0.895f, -2.0f, 2.0f)
reflectiveCurveToRelative(0.895f, 2.0f, 2.0f, 2.0f)
reflectiveCurveToRelative(2.0f, -0.895f, 2.0f, -2.0f)
reflectiveCurveToRelative(-0.895f, -2.0f, -2.0f, -2.0f)
close()
moveTo(15.5f, 18.0f)
horizontalLineToRelative(-7.0f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
verticalLineToRelative(-5.0f)
curveToRelative(0.0f, -1.93f, 1.57f, -3.5f, 3.5f, -3.5f)
horizontalLineToRelative(0.196f)
lineToRelative(0.885f, -1.331f)
curveToRelative(0.278f, -0.418f, 0.747f, -0.669f, 1.249f, -0.669f)
horizontalLineToRelative(2.34f)
curveToRelative(0.502f, 0.0f, 0.971f, 0.251f, 1.249f, 0.669f)
lineToRelative(0.885f, 1.331f)
horizontalLineToRelative(0.196f)
curveToRelative(1.93f, 0.0f, 3.5f, 1.57f, 3.5f, 3.5f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 1.93f, -1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(16.0f, 9.5f)
curveToRelative(0.0f, -0.275f, -0.225f, -0.5f, -0.5f, -0.5f)
horizontalLineToRelative(-7.0f)
curveToRelative(-0.275f, 0.0f, -0.5f, 0.225f, -0.5f, 0.5f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 0.275f, 0.225f, 0.5f, 0.5f, 0.5f)
horizontalLineToRelative(7.0f)
curveToRelative(0.275f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f)
verticalLineToRelative(-5.0f)
close()
}
}
.build()
return _cameraViewfinder!!
}
private var _cameraViewfinder: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,778 |
icons
|
MIT License
|
baselibrary/src/main/java/com/brilliantzhao/baselibrary/widget/NoScrollGridView.kt
|
brilliantzhao
| 120,424,717 | false | null |
package com.brilliantzhao.baselibrary.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.GridView
/**
* description:不会滚动的gridview
* Created by xsf
* on 2016.04.15:04
*/
class NoScrollGridView : GridView {
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}
public override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val expandSpec = View.MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE shr 2, View.MeasureSpec.AT_MOST)
super.onMeasure(widthMeasureSpec, expandSpec)
}
}
| 0 |
Kotlin
|
3
| 12 |
ce8e0eff102f73d9f92c6708533d694834ce8e54
| 796 |
AndFrameWork
|
Apache License 2.0
|
data/auth/src/main/java/com/loryblu/data/auth/api/LoginApi.kt
|
loryblu
| 665,795,911 | false |
{"Kotlin": 315219}
|
package com.loryblu.data.auth.api
import com.loryblu.data.auth.model.LoginRequest
import com.loryblu.data.auth.model.SignInResult
interface LoginApi {
suspend fun loginUser(loginRequest: LoginRequest) : SignInResult
}
| 0 |
Kotlin
|
4
| 8 |
4eaeb70fe253a12ec4ad3b438aa750dad3c6b548
| 223 |
loryblu-android
|
MIT License
|
src/main/kotlin/no/nav/sykdig/digitalisering/ferdigstilling/oppgave/OppgaveClient.kt
|
navikt
| 499,488,833 | false |
{"Kotlin": 296670, "Dockerfile": 127, "Shell": 102}
|
package no.nav.sykdig.digitalisering.ferdigstilling.oppgave
import net.logstash.logback.argument.StructuredArguments.kv
import no.nav.sykdig.applog
import no.nav.sykdig.digitalisering.exceptions.IkkeTilgangException
import no.nav.sykdig.digitalisering.exceptions.NoOppgaveException
import no.nav.sykdig.digitalisering.getFristForFerdigstillingAvOppgave
import no.nav.sykdig.digitalisering.saf.graphql.SafJournalpost
import no.nav.sykdig.digitalisering.saf.graphql.TEMA_SYKMELDING
import no.nav.sykdig.objectMapper
import no.nav.sykdig.securelog
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.retry.annotation.Retryable
import org.springframework.stereotype.Component
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.HttpServerErrorException
import org.springframework.web.client.RestTemplate
import java.time.LocalDate
import java.util.UUID
private const val OPPGAVETYPE = "JFR"
private const val PRIORITET_NORM = "NORM"
private const val BEHANDLES_AV_APPLIKASJON = "SMD"
private const val TILDELT_ENHETSNR = "0393"
private const val OPPRETTET_AV_ENHETSNR = "9999"
private const val BEHANDLINGS_TYPE_UTLAND = "ae0106"
@Component
class OppgaveClient(
@Value("\${oppgave.url}") private val url: String,
private val oppgaveRestTemplate: RestTemplate,
private val oppgaveM2mRestTemplate: RestTemplate,
) {
val log = applog()
val secureLog = securelog()
fun ferdigstillOppgave(
oppgaveId: String,
sykmeldingId: String,
) {
val oppgave = getOppgave(oppgaveId, sykmeldingId)
if (oppgave.status == Oppgavestatus.FERDIGSTILT || oppgave.status == Oppgavestatus.FEILREGISTRERT) {
log.info("Oppgave med id $oppgaveId er allerede ferdigstilt")
} else {
ferdigstillOppgave(oppgaveId, sykmeldingId, oppgave.versjon)
log.info("Ferdigstilt oppgave med id $oppgaveId i Oppgave")
}
}
@Retryable
fun getOppgaveM2m(
oppgaveId: String,
sykmeldingId: String,
): GetOppgaveResponse {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = sykmeldingId
try {
val response =
oppgaveM2mRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.GET,
HttpEntity<Any>(headers),
GetOppgaveResponse::class.java,
)
return response.body ?: throw NoOppgaveException("Fant ikke oppgaver på journalpostId $oppgaveId")
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn("syk-dig-backend har ikke tilgang til oppgaveId $oppgaveId: ${e.message}")
throw IkkeTilgangException("syk-dig-backend har ikke tilgang til oppgave")
} else {
log.error(
"HttpClientErrorException med responskode ${e.statusCode.value()} fra Oppgave: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error("HttpServerErrorException med responskode ${e.statusCode.value()} fra Oppgave: ${e.message}", e)
throw e
} catch (e: Exception) {
log.error("Other Exception fra Oppgave: ${e.message}", e)
throw e
}
}
@Retryable
fun getOppgave(
oppgaveId: String,
sykmeldingId: String,
): GetOppgaveResponse {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = sykmeldingId
try {
val response =
oppgaveRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.GET,
HttpEntity<Any>(headers),
GetOppgaveResponse::class.java,
)
return response.body ?: throw NoOppgaveException("Fant ikke oppgaver på journalpostId $oppgaveId")
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn("Veileder har ikke tilgang til oppgaveId $oppgaveId: ${e.message}")
throw IkkeTilgangException("Veileder har ikke tilgang til oppgave")
} else {
log.error(
"HttpClientErrorException med responskode ${e.statusCode.value()} fra Oppgave: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error("HttpServerErrorException med responskode ${e.statusCode.value()} fra Oppgave: ${e.message}", e)
throw e
} catch (e: Exception) {
log.error("Other Exception fra Oppgave: ${e.message}", e)
throw e
}
}
@Retryable
fun getOppgaver(
journalpostId: String,
journalpost: SafJournalpost,
): List<AllOppgaveResponse> {
val headers = HttpHeaders()
val urlWithParams = urlWithParams(journalpostId, journalpost)
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = UUID.randomUUID().toString()
log.info("Kaller oppgaveRestTemplate.exchange med URL: $urlWithParams og journalpostId: $journalpostId")
try {
val response =
oppgaveRestTemplate.exchange(
urlWithParams,
HttpMethod.GET,
HttpEntity<Any>(headers),
AllOppgaveResponses::class.java,
)
log.info("Mottok respons for journalpostId $journalpostId med antall oppgaver: ${response.body?.oppgaver?.size ?: "ingen"}")
return response.body?.oppgaver ?: throw NoOppgaveException("Fant ikke oppgaver på journalpostId $journalpostId")
} catch (e: HttpClientErrorException) {
log.error(
"HttpClientErrorException med responskode ${e.statusCode.value()} fra journalpostId $journalpostId. Detaljer: ${e.message}",
e,
)
throw e
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException med responskode ${e.statusCode.value()} fra journalpostId $journalpostId. Detaljer: ${e.message}",
e,
)
throw e
} catch (e: Exception) {
log.error("Generell Exception blir kastet ved henting av oppgaver på journalpostId $journalpostId. Detaljer: ${e.message}", e)
throw e
}
}
private fun urlWithParams(
journalpostId: String,
journalpost: SafJournalpost,
): String {
if (journalpost.bruker == null) throw NoOppgaveException("ingen oppgaver på journalpostId $journalpost fordi bruker er null")
return "$url?journalpostId=$journalpostId&statuskategori=AAPEN"
}
@Retryable
private fun ferdigstillOppgave(
oppgaveId: String,
sykmeldingId: String,
oppgaveVersjon: Int,
) {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = sykmeldingId
val body =
PatchFerdigStillOppgaveRequest(
versjon = oppgaveVersjon,
status = Oppgavestatus.FERDIGSTILT,
id = oppgaveId.toInt(),
)
try {
oppgaveRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.PATCH,
HttpEntity(body, headers),
String::class.java,
)
log.info("Ferdigstilt oppgave $oppgaveId for sykmelding $sykmeldingId")
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn("Veileder har ikke tilgang til å ferdigstille oppgaveId $oppgaveId: ${e.message}")
throw IkkeTilgangException("Veileder har ikke tilgang til oppgave")
} else {
log.error(
"HttpClientErrorException for oppgaveId $oppgaveId med responskode " +
"${e.statusCode.value()} fra Oppgave ved ferdigstilling: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException for oppgaveId $oppgaveId med responskode " +
"${e.statusCode.value()} fra Oppgave ved ferdigstilling: ${e.message}",
e,
)
throw e
}
}
@Retryable
fun ferdigstillJournalføringsoppgave(
oppgaveId: Int,
oppgaveVersjon: Int,
journalpostId: String,
) {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = UUID.randomUUID().toString()
val body =
PatchFerdigStillOppgaveRequest(
versjon = oppgaveVersjon,
status = Oppgavestatus.FERDIGSTILT,
id = oppgaveId,
)
try {
oppgaveRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.PATCH,
HttpEntity(body, headers),
String::class.java,
)
log.info(
"Ferdigstilt journalføringsopoppgave {} {}",
kv("journalpostId", journalpostId),
kv("oppgaveId", oppgaveId),
)
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException for oppgaveId $oppgaveId og journalpostId $journalpostId med responskode " +
"${e.statusCode.value()} fra Oppgave ved ferdigstilling: ${e.message}",
e,
)
throw e
} catch (e: Exception) {
log.error("Exception. Fra journalpost: ${e.message}", e)
throw e
}
}
fun oppdaterOppgaveM2m(
oppdaterOppgaveRequest: OppdaterOppgaveRequest,
sykmeldingId: String,
) {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = sykmeldingId
val oppgaveId = oppdaterOppgaveRequest.id
try {
oppgaveM2mRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.PATCH,
HttpEntity(oppdaterOppgaveRequest, headers),
String::class.java,
)
log.info("OppdaterOppgave oppgave $oppgaveId for sykmelding $sykmeldingId")
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn(
"Syk-dig-backend har ikke tilgang til å " +
"oppdaterOppgave oppgaveId $oppgaveId: ${e.message}",
)
throw IkkeTilgangException("Syk-dig har ikke tilgang til oppgave")
} else {
log.error(
"HttpClientErrorException for oppgaveId $oppgaveId med responskode ${e.statusCode.value()} " +
"fra Oppgave ved oppdaterOppgave: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException for oppgaveId $oppgaveId med responskode ${e.statusCode.value()} " +
"fra Oppgave ved oppdaterOppgave: ${e.message}",
e,
)
throw e
}
}
@Retryable
fun oppdaterGosysOppgave(
oppgaveId: String,
sykmeldingId: String,
oppgaveVersjon: Int,
oppgaveStatus: Oppgavestatus,
oppgaveBehandlesAvApplikasjon: String,
oppgaveTilordnetRessurs: String,
beskrivelse: String?,
) {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = sykmeldingId
val body =
PatchToGosysOppgaveRequest(
versjon = oppgaveVersjon,
status = oppgaveStatus,
id = oppgaveId.toInt(),
behandlesAvApplikasjon = oppgaveBehandlesAvApplikasjon,
tilordnetRessurs = oppgaveTilordnetRessurs,
beskrivelse = beskrivelse,
)
try {
oppgaveRestTemplate.exchange(
"$url/$oppgaveId",
HttpMethod.PATCH,
HttpEntity(body, headers),
String::class.java,
)
log.info("OppdaterOppgave oppgave $oppgaveId for sykmelding $sykmeldingId")
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn(
"Veileder $oppgaveTilordnetRessurs har ikke tilgang til å " +
"oppdaterOppgave oppgaveId $oppgaveId: ${e.message}",
)
throw IkkeTilgangException("Veileder har ikke tilgang til oppgave")
} else {
log.error(
"HttpClientErrorException for oppgaveId $oppgaveId med responskode ${e.statusCode.value()} " +
"fra Oppgave ved oppdaterOppgave: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException for oppgaveId $oppgaveId med responskode ${e.statusCode.value()} " +
"fra Oppgave ved oppdaterOppgave: ${e.message}",
e,
)
throw e
}
}
fun opprettOppgave(
journalpostId: String,
aktoerId: String,
): GetOppgaveResponse {
val headers = HttpHeaders()
val xCorrelationId = UUID.randomUUID().toString()
headers.contentType = MediaType.APPLICATION_JSON
headers["X-Correlation-ID"] = xCorrelationId
try {
val result =
oppgaveRestTemplate.exchange(
url,
HttpMethod.POST,
HttpEntity(
CreateOppgaveRequest(
aktoerId = aktoerId,
journalpostId = journalpostId,
tema = TEMA_SYKMELDING,
oppgavetype = OPPGAVETYPE,
prioritet = PRIORITET_NORM,
opprettetAvEnhetsnr = OPPRETTET_AV_ENHETSNR,
aktivDato = LocalDate.now(),
behandlesAvApplikasjon = BEHANDLES_AV_APPLIKASJON,
behandlingstype = BEHANDLINGS_TYPE_UTLAND,
fristFerdigstillelse = getFristForFerdigstillingAvOppgave(LocalDate.now()),
tildeltEnhetsnr = TILDELT_ENHETSNR,
),
headers,
),
GetOppgaveResponse::class.java,
)
secureLog.info("OpprettOppgave: $journalpostId: ${objectMapper.writeValueAsString(result.body)}, aktørId: $aktoerId")
val oppgave = result.body!!
log.info("OpprettOppgave fra journalpostId: $journalpostId med oppgaveId: ${oppgave.id}")
return oppgave
} catch (e: HttpClientErrorException) {
if (e.statusCode.value() == 401 || e.statusCode.value() == 403) {
log.warn(
"Veileder har ikke tilgang til å opprette oppgaveId $journalpostId " +
"med correlation id $xCorrelationId: ${e.message}",
)
throw IkkeTilgangException("Veileder har ikke tilgang til å opprette oppgave")
} else {
log.error(
"HttpClientErrorException for oppgaveId $journalpostId med responskode " +
"${e.statusCode.value()} fra Oppgave ved createOppgave med correlation id $xCorrelationId: ${e.message}",
e,
)
throw e
}
} catch (e: HttpServerErrorException) {
log.error(
"HttpServerErrorException for oppgaveId $journalpostId med responskode" +
" ${e.statusCode.value()} fra Oppgave ved createOppgave med correlation id $xCorrelationId: ${e.message}",
e,
)
throw e
} catch (e: Exception) {
log.error(
"Kunne ikke opprette oppgave med på journalpostId $journalpostId " +
"ved createOppgave med correlation id $xCorrelationId: ${e.message}",
e,
)
throw e
}
}
}
| 1 |
Kotlin
|
0
| 1 |
2f20081188d61fc970c52f597197086e8e882b4c
| 17,440 |
syk-dig-backend
|
MIT License
|
Observer/src/main/kotlin/impl/SubjectImpl.kt
|
AaronChuang
| 208,242,423 | false | null |
package impl
import AbstractSubject
// 主題實作
class SubjectImpl: AbstractSubject() {
var mSubjectState:String = ""
set(value) {
field = value
notifyAllObservers()
}
}
| 0 |
Kotlin
|
0
| 0 |
9e31b8065a7b98e30d93033fae92d0381c17ef34
| 210 |
Kotlin-DesignPatternExample
|
MIT License
|
src/main/kotlin/me/raino/faucet/api/region/Negative.kt
|
058c37a272bed3464d47f0b01038a16a
| 46,979,268 | false | null |
package me.raino.faucet.api.region
import com.flowpowered.math.vector.Vector2d
import com.flowpowered.math.vector.Vector3d
class Negative(val region: Region) : Region {
override fun contains(point: Vector3d): Boolean = !region.contains(point)
override fun contains(point: Vector2d): Boolean = !region.contains(point)
}
| 0 |
Kotlin
|
0
| 0 |
ea5a31711bc2708126a1ef0c16354c29b99f0d3c
| 331 |
Faucet
|
MIT License
|
prj-website/src/jsMain/kotlin/state/LogoffApplication.kt
|
simonegiacomelli
| 473,571,649 | false | null |
package state
import api.names.ApiAcLogoffRequest
import kotlinx.browser.window
import kotlinx.coroutines.withTimeout
import rpc.send
fun JsState.logoffApplication() = spinner {
runCatching { withTimeout(1000) { session_id?.also { ApiAcLogoffRequest(it).send() } } }
sessionOrNull = null
window.setTimeout({ coroutine.launch { startupApplication() } }, 1)
}
| 0 |
Kotlin
|
1
| 0 |
8a33826566229a025664af7e5452b664efdf6a4c
| 371 |
kotlin-mpp-starter
|
Apache License 2.0
|
cli-bot/src/main/kotlin/io/github/serpro69/kfaker/app/KFaker.kt
|
serpro69
| 174,969,439 | false | null |
package io.github.serpro69.kfaker.app
import io.github.serpro69.kfaker.app.subcommands.List
import io.github.serpro69.kfaker.app.subcommands.Lookup
import picocli.CommandLine
import kotlin.system.exitProcess
@CommandLine.Command(
name = "faker-bot",
description = [
"helps to quickly find required faker functionality",
"see https://github.com/serpro69/kotlin-faker/README.md for more installation and usage examples"
],
version = [
"faker: 2.0.0-rc.2", // 2.0.0-rc.2 is a placeholder that will be temporarily replaced during compilation
"faker-bot: 2.0.0-rc.2",
"Built with picocli ${CommandLine.VERSION}",
"JVM: \${java.version} (\${java.vendor} \${java.vm.name} \${java.vm.version})",
"OS: \${os.name} \${os.version} \${os.arch}"
],
synopsisHeading = "Usage:%n",
descriptionHeading = "%nDescription:%n",
parameterListHeading = "%nParameters:%n",
optionListHeading = "%nOptions:%n",
commandListHeading = "%nCommands:%n",
subcommands = [
List::class,
Lookup::class
]
)
object KFaker : Runnable {
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["display this help message"])
private var usageHelpRequested: Boolean = false
@CommandLine.Option(names = ["--version"], versionHelp = true, description = ["display version info"])
private var versionHelpRequested: Boolean = false
@CommandLine.Spec
lateinit var spec: CommandLine.Model.CommandSpec
override fun run() {
throw CommandLine.ParameterException(spec.commandLine(), "Specify parameter")
}
}
fun main(args: Array<String>) {
val cli = CommandLine(KFaker)
exitProcess(cli.execute(*args))
}
| 34 | null |
42
| 462 |
22b0f971c9f699045b30d913c6cbca02060ed9b3
| 1,749 |
kotlin-faker
|
MIT License
|
protocol/kotlin/src/solarxr_protocol/rpc/SerialTrackerGetInfoRequest.kt
|
SlimeVR
| 456,320,520 | false |
{"Rust": 790111, "Java": 650829, "TypeScript": 507384, "C++": 434772, "Kotlin": 356034, "PowerShell": 959, "Shell": 910, "Nix": 587}
|
// automatically generated by the FlatBuffers compiler, do not modify
package solarxr_protocol.rpc
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
/**
* Sends the GET INFO cmd to the current tracker on the serial monitor
*/
@Suppress("unused")
class SerialTrackerGetInfoRequest : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : SerialTrackerGetInfoRequest {
__init(_i, _bb)
return this
}
companion object {
@JvmStatic
fun validateVersion() = Constants.FLATBUFFERS_22_10_26()
@JvmStatic
fun getRootAsSerialTrackerGetInfoRequest(_bb: ByteBuffer): SerialTrackerGetInfoRequest = getRootAsSerialTrackerGetInfoRequest(_bb, SerialTrackerGetInfoRequest())
@JvmStatic
fun getRootAsSerialTrackerGetInfoRequest(_bb: ByteBuffer, obj: SerialTrackerGetInfoRequest): SerialTrackerGetInfoRequest {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
@JvmStatic
fun startSerialTrackerGetInfoRequest(builder: FlatBufferBuilder) = builder.startTable(0)
@JvmStatic
fun endSerialTrackerGetInfoRequest(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 11 |
Rust
|
20
| 19 |
60f3146f914e2a9e35d759a8146be213e715d6d2
| 1,401 |
SolarXR-Protocol
|
Apache License 2.0
|
languages/python/src/main/kotlin/io/vrap/codegen/languages/python/model/PythonModelRenderer.kt
|
commercetools
| 136,635,215 | false | null |
/**
* Copyright 2021 <NAME>
*/
package io.vrap.codegen.languages.python.model
import io.vrap.codegen.languages.extensions.discriminatorProperty
import io.vrap.codegen.languages.extensions.getSuperTypes
import io.vrap.codegen.languages.extensions.isPatternProperty
import io.vrap.codegen.languages.extensions.sortedByTopology
import io.vrap.codegen.languages.python.pyGeneratedComment
import io.vrap.codegen.languages.python.snakeCase
import io.vrap.codegen.languages.python.toDocString
import io.vrap.codegen.languages.python.toLineComment
import io.vrap.codegen.languages.python.toRelativePackageName
import io.vrap.rmf.codegen.di.AllAnyTypes
import io.vrap.rmf.codegen.io.TemplateFile
import io.vrap.rmf.codegen.rendering.FileProducer
import io.vrap.rmf.codegen.rendering.utils.escapeAll
import io.vrap.rmf.codegen.rendering.utils.keepIndentation
import io.vrap.rmf.codegen.types.VrapEnumType
import io.vrap.rmf.codegen.types.VrapObjectType
import io.vrap.rmf.codegen.types.VrapScalarType
import io.vrap.rmf.codegen.types.VrapTypeProvider
import io.vrap.rmf.raml.model.types.AnyType
import io.vrap.rmf.raml.model.types.IntersectionType
import io.vrap.rmf.raml.model.types.NilType
import io.vrap.rmf.raml.model.types.ObjectType
import io.vrap.rmf.raml.model.types.StringInstance
import io.vrap.rmf.raml.model.types.StringType
import io.vrap.rmf.raml.model.types.UnionType
import io.vrap.rmf.raml.model.util.StringCaseFormat
class PythonModelRenderer constructor(
override val vrapTypeProvider: VrapTypeProvider,
@AllAnyTypes var allAnyTypes: List<AnyType>
) : PyObjectTypeExtensions, FileProducer {
override fun produceFiles(): List<TemplateFile> {
return allAnyTypes.filter { it is ObjectType || (it is StringType && it.pattern == null) }
.groupBy {
it.moduleName()
}
.map { entry: Map.Entry<String, List<AnyType>> ->
buildModule(entry.key, entry.value)
}
.toList()
}
private fun buildModule(moduleName: String, types: List<AnyType>): TemplateFile {
var sortedTypes = types.sortedByTopology(AnyType::getSuperTypes)
val content = """
|$pyGeneratedComment
|
|${sortedTypes.getImportsForModule(moduleName)}
|
|${sortedTypes.getTypeImportsForModule(moduleName)}
|
|${getExportedVariables(types)}
|
|${sortedTypes.map { it.renderAnyType() }.joinToString(separator = "\n")}
""".trimMargin().keepIndentation()
var filename = moduleName.split(".").joinToString(separator = "/")
return TemplateFile(content, filename + ".py")
}
private fun AnyType.renderAnyType(): String {
return when (this) {
is ObjectType -> this.renderObjectType()
is StringType -> this.renderStringType()
else -> throw IllegalArgumentException("unhandled case ${this.javaClass}")
}
}
/**
* Render the __all__ = [...] statement on the top of the file to indicate
* all the objects we want to export if `from x import *` is used.
*/
private fun getExportedVariables(types: List<AnyType>): String {
return types
.map { "'${it.toPythonVrapType().simplePyName()}'" }
.sorted()
.joinToString(prefix = "__all__ = [", postfix = "]\n", separator = ",\n")
}
private fun ObjectType.renderObjectType(): String {
val isDict = allProperties.all { it.isPatternProperty() }
if (isDict) {
val valueType = if (allProperties.size > 0) allProperties[0].type.renderTypeExpr() else "typing.Any"
return """
|class $name(typing.Dict[str, $valueType]):
| pass
""".trimMargin()
} else {
return """
|class ${name}${renderExtendsExpr()}:
| <${toDocString().escapeAll()}>
| <${renderPropertyDecls()}>
|
| <${renderInitFunction()}>
| <${renderSerializationMethods()}>
""".trimMargin()
}
}
/**
* Renders the optional base class expression for the model class.
*/
fun ObjectType.renderExtendsExpr(): String {
return type?.toVrapType()?.simplePyName()?.let { "($it)" } ?: "(_BaseType)"
}
/**
* Renders the attribute of this model as type annotations
*/
fun ObjectType.renderPropertyDecls(): String {
return PyClassProperties(false)
.filter {
!it.isPatternProperty()
}
.map {
val comment: String = it.type.toLineComment().escapeAll()
if (it.required) {
"""
|<$comment>
|${it.name.snakeCase()}: ${it.type.renderTypeExpr()}
""".trimMargin()
} else {
"""
|<$comment>
|${it.name.snakeCase()}: typing.Optional[${it.type.renderTypeExpr()}]
""".trimMargin()
}
}
.joinToString("\n")
}
/**
* Create the __init__ method of the class
*/
fun ObjectType.renderInitFunction(): String {
var attributes = arrayOf("self")
var kwargs = PyClassProperties(true)
.filter { !it.isPatternProperty() }
.map {
if (it.required) {
"${it.name.snakeCase()}: ${it.type.renderTypeExpr()}"
} else {
"${it.name.snakeCase()}: typing.Optional[${it.type.renderTypeExpr()}] = None"
}
}
if (kwargs.size > 0) {
attributes += arrayOf("*")
attributes += kwargs
}
if (PyClassProperties(true).filter { it.isPatternProperty() }.size > 0) {
attributes += arrayOf("**kwargs")
}
var initArgs = mutableListOf<String>()
val passProperties = PyClassProperties(true) - PyClassProperties(false)
passProperties.filter { !it.isPatternProperty() }.forEach {
initArgs.add("${it.name.snakeCase()}=${it.name.snakeCase()}")
}
val property = discriminatorProperty()
var cleanKwargsStatement = ""
if (property != null && discriminatorValue != null) {
//
val propVrapType = property.type.toVrapType()
val dVal: String = when (propVrapType) {
is VrapEnumType -> "${propVrapType.simpleClassName}.${StringCaseFormat.UPPER_UNDERSCORE_CASE.apply(discriminatorValue)}"
else -> "\"${discriminatorValue}\""
}
initArgs.add("${property.name.snakeCase()}=$dVal")
if (passProperties.filter { it.isPatternProperty() }.size > 0) {
cleanKwargsStatement = """kwargs.pop("${property.name.snakeCase()}", None)"""
}
}
if (passProperties.filter { it.isPatternProperty() }.size > 0) {
initArgs.add("**kwargs")
}
val attrStr = attributes.joinToString(separator = ", ")
return """
|def __init__($attrStr):
| ${renderInitAssignments()}
| ${cleanKwargsStatement}
| super().__init__(${initArgs.joinToString(separator = ", ")})
""".trimMargin().keepIndentation()
}
fun ObjectType.renderSerializationMethods(): String {
val schemaType = this.toSchemaVrapType()
if (schemaType !is VrapObjectType) return ""
val packageName = schemaType.`package`.toRelativePackageName(moduleName())
val switchStatement: String
if (this.isDiscriminated()) {
switchStatement = allAnyTypes.getTypeInheritance(this)
.filterIsInstance<ObjectType>()
.filter { !it.discriminatorValue.isNullOrEmpty() }
.map {
val vrapSubType = it.toSchemaVrapType() as VrapObjectType
val module = vrapSubType
.`package`
.toRelativePackageName(moduleName())
"""
|if data["${discriminator()}"] == "${it.discriminatorValue}":
| from $module import ${vrapSubType.simplePyName()}
| return ${vrapSubType.simplePyName()}().load(data)
""".trimMargin()
}
.joinToString("\n")
return """
|@classmethod
|def deserialize(cls, data: typing.Dict[str, typing.Any]) -\> "$name":
|${switchStatement.prependIndent(" ")}
|
|def serialize(self) -\> typing.Dict[str, typing.Any]:
| from $packageName import ${schemaType.simpleClassName}
| return ${schemaType.simpleClassName}().dump(self)
""".trimMargin()
}
return """
|@classmethod
|def deserialize(cls, data: typing.Dict[str, typing.Any]) -\> "$name":
| from $packageName import ${schemaType.simpleClassName}
| return ${schemaType.simpleClassName}().load(data)
|
|def serialize(self) -\> typing.Dict[str, typing.Any]:
| from $packageName import ${schemaType.simpleClassName}
| return ${schemaType.simpleClassName}().dump(self)
""".trimMargin()
}
fun ObjectType.renderInitAssignments(): String {
return PyClassProperties(false)
.map {
if (it.isPatternProperty()) {
"self.__dict__.update(kwargs)"
} else {
"self.${it.name.snakeCase()} = ${it.name.snakeCase()}"
}
}
.joinToString("\n ")
}
/**
* Renders the Python type annotation this types type.
*/
fun AnyType.renderTypeExpr(): String {
return when (this) {
is UnionType -> oneOf.map { it.renderTypeExpr() }.joinToString(prefix = "typing.Union[", separator = ", ", postfix = "]")
is IntersectionType -> allOf.map { it.renderTypeExpr() }.joinToString(" & ")
is NilType -> "None"
else -> toVrapType().pyTypeName()
}
}
private fun StringType.renderStringType(): String {
val vrapType = this.toVrapType()
return when (vrapType) {
is VrapEnumType ->
return """
|class ${vrapType.simpleClassName}(enum.Enum):
| <${toDocString().escapeAll()}>
| <${this.renderEnumValues()}>
|
|
""".trimMargin()
is VrapScalarType -> """
|${this.name} = ${vrapType.scalarType}
""".trimMargin()
else -> ""
}
}
private fun StringType.renderEnumValues(): String = enumValues()
.map { "${StringCaseFormat.UPPER_UNDERSCORE_CASE.apply(it)} = '$it'" }
.joinToString("\n")
private fun StringType.enumValues() = enum?.filter { it is StringInstance }
?.map { (it as StringInstance).value }
?.filterNotNull() ?: listOf()
}
| 23 | null |
6
| 14 |
2f8846e5dee3ced5f00613e2f6a382e5d818be4d
| 11,229 |
rmf-codegen
|
Apache License 2.0
|
widgets/src/iosMain/kotlin/dev/icerock/moko/widgets/listWidgetViewFactory.kt
|
ATchernov
| 223,135,697 | true |
{"Kotlin": 225543, "Swift": 103744, "Ruby": 1136}
|
/*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets
import dev.icerock.moko.units.UnitTableViewDataSource
import dev.icerock.moko.widgets.core.VFC
import dev.icerock.moko.widgets.core.bind
import dev.icerock.moko.widgets.utils.applyBackground
import dev.icerock.moko.widgets.utils.toEdgeInsets
import kotlinx.cinterop.readValue
import platform.CoreGraphics.CGRectZero
import platform.UIKit.UITableView
import platform.UIKit.UITableViewAutomaticDimension
import platform.UIKit.UITableViewStyle
import platform.UIKit.translatesAutoresizingMaskIntoConstraints
actual var listWidgetViewFactory: VFC<ListWidget> = { viewController, widget ->
// TODO add styles support
val style = widget.style
val tableView = UITableView(
frame = CGRectZero.readValue(),
style = UITableViewStyle.UITableViewStylePlain
)
val unitDataSource = UnitTableViewDataSource(tableView)
with(tableView) {
translatesAutoresizingMaskIntoConstraints = false
dataSource = unitDataSource
rowHeight = UITableViewAutomaticDimension
estimatedRowHeight = UITableViewAutomaticDimension
applyBackground(style.background)
style.padding?.toEdgeInsets()?.also {
contentInset = it
}
}
widget.items.bind { unitDataSource.unitItems = it }
tableView
}
| 0 | null |
0
| 0 |
560af260a9813724fd8e53b5c7ea0691e3b5fb46
| 1,417 |
moko-widgets
|
Apache License 2.0
|
app/src/main/java/com/myapp/data/remote/TokenAuthenticator.kt
|
trietbui85
| 238,267,619 | false | null |
package com.myapp.data.remote
import com.myapp.data.repo.AccessTokenItem
import com.myapp.data.repo.AccountRepository
import com.myapp.utils.addBearerToken
import com.myapp.utils.getAuthorization
import com.myapp.utils.isUnauthorized
import kotlinx.coroutines.runBlocking
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import timber.log.Timber
class TokenAuthenticator(
private val accountRepository: AccountRepository
) : Authenticator {
override fun authenticate(
route: Route?,
response: Response
): Request? {
Timber.d("Found 401 request - need to refresh its token")
if (getResponseCount(response) >= RETRY_LIMIT_COUNT) {
Timber.d("Failed $RETRY_LIMIT_COUNT times, giving up")
return null
}
// We need to have a token in order to refresh it.
val token = runBlocking {
accountRepository.getTokenFromCache()
}
synchronized(this) {
val newToken = runBlocking {
accountRepository.getTokenFromCache()
}
// Check if the request made was previously made as an authenticated request.
if (response.isUnauthorized() || response.request.getAuthorization() != null) {
response.priorResponse
// If the token has changed since the request was made, use the new token.
if (newToken != null && newToken != token) {
return newRequestWithAccessToken(response.request, newToken)
}
val updatedToken = runBlocking {
accountRepository.refreshToken()
} ?: return null
// Retry the request with the new token.
return newRequestWithAccessToken(response.request, updatedToken)
}
}
return null
}
private fun getResponseCount(response: Response): Int {
var result = 1
var priorResponse = response.priorResponse
while (priorResponse != null) {
result++
priorResponse = priorResponse.priorResponse
}
return result
}
private fun newRequestWithAccessToken(
request: Request,
accessToken: AccessTokenItem
): Request {
Timber.d("After have new token=$accessToken, continue request=$request")
return request.newBuilder()
.addBearerToken(accessToken.bearerToken)
.build()
}
private companion object {
// Only retry 3 times
const val RETRY_LIMIT_COUNT = 3
}
}
| 2 |
Kotlin
|
0
| 1 |
6e6a7d6a41ca267d3491cd117ffbc17e284cb26e
| 2,364 |
survey_app
|
MIT License
|
app/src/main/java/com/coder/ffmpegtest/service/FFmpegCommandService.kt
|
AnJoiner
| 228,573,666 | false | null |
package com.coder.ffmpegtest.service
import android.app.IntentService
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.coder.ffmpeg.annotation.MediaAttribute
import com.coder.ffmpeg.call.CommonCallBack
import com.coder.ffmpeg.jni.FFmpegCommand
import com.coder.ffmpeg.utils.CommandParams
import com.coder.ffmpegtest.utils.FileUtils
import com.coder.ffmpegtest.utils.ToastUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.util.*
/**
* @author: AnJoiner
* @datetime: 20-6-28
*/
class FFmpegCommandService : IntentService("") {
companion object{
val TAG = "FFmpegCommandService"
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG,"onStartCommand")
FileUtils.copy2Memory(this, "test.mp4")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
Log.e(TAG,"onDestroy")
super.onDestroy()
}
override fun onHandleIntent(intent: Intent?) {
val videoPath = File(externalCacheDir, "test.mp4").absolutePath
val output = File(externalCacheDir, "leak.avi").absolutePath
// val cmd = "ffmpeg -y -i %s -b:v 600k %s"
val command = CommandParams()
.append("-i")
.append(videoPath)
.append("-b:v")
.append("600k")
.append(output)
.get()
FFmpegCommand.runCmd(command, callback("测试内存抖动", output))
}
private fun callback(msg: String, targetPath: String?): CommonCallBack? {
return object : CommonCallBack() {
override fun onStart() {
Log.d("FFmpegCmd", "onStart")
}
override fun onComplete() {
Log.d("FFmpegCmd", "onComplete")
}
override fun onCancel() {
Log.d("FFmpegCmd", "Cancel")
}
override fun onProgress(progress: Int, pts: Long) {
Log.d("FFmpegCmd", progress.toString() + "")
}
override fun onError(errorCode: Int, errorMsg: String?) {
Log.d("FFmpegCmd", errorMsg+"")
}
}
}
}
| 28 | null |
154
| 820 |
2e48031c833e37156cd26e3d7c3491ba1c53bdd1
| 2,359 |
FFmpegCommand
|
Apache License 2.0
|
app/src/main/java/com/provatokenlab/home/adapter/HomeAdapter.kt
|
carlosferreira01
| 242,584,109 | false | null |
package com.provatokenlab.home.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.domain.movie.model.Movie
import com.provatokenlab.R
import com.provatokenlab.home.adapter.holder.HomeViewHolder
import com.provatokenlab.shared.adapter.RecyclerViewAdapter
import com.provatokenlab.shared.images.LoadImages
class HomeAdapter(
private val mContext: Context,
private var mList: List<Movie>): RecyclerViewAdapter<HomeViewHolder, Movie>(mList) {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): HomeViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.layout_adapter_home, viewGroup, false)
return createItemClick(view, HomeViewHolder(view))
}
override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
val movie = mList[position]
holder.mTextNameMovie.text = movie.title
holder.mTextGenres.text = movie.genres.component1()
holder.mTextRelease.text = String.format(
mContext.resources.getString(R.string.text_release_concatenate),
movie.date.substring(0,4)
)
holder.mTextAverage.text = movie.average.toString()
if(movie.image != null) {
LoadImages.loadImageLoaderOnImageView(movie.image, holder.mImageMovie)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e09f6f94c393ea8a7bfaa647bbb1e3ed780947f6
| 1,396 |
Desafio-App
|
MIT License
|
src/main/kotlin/ru/kosolapov/course/configuration/Databases.kt
|
Zymik
| 637,872,394 | false | null |
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import io.ktor.server.application.*
import org.jetbrains.exposed.sql.Database
import ru.kosolapov.course.table.Tables
fun Application.configureDatabase() {
Database.connect(hikari())
Tables.init()
}
private fun Application.hikari(): HikariDataSource {
val config = HikariConfig()
config.driverClassName = "org.postgresql.Driver"
config.jdbcUrl = environment.config.property("database.url").getString()
config.username = environment.config.property("database.user").getString()
config.password = environment.config.property("database.password").getString()
config.maximumPoolSize = environment.config.property("database.maximum_pool_size").getString().toInt()
config.isAutoCommit = false
config.transactionIsolation = environment.config.property("database.transaction_isolation").getString()
config.validate()
return HikariDataSource(config)
}
| 0 |
Kotlin
|
0
| 0 |
de6beb0c5ee63c5afad164e6169bb3a6f8c7944a
| 972 |
course-api
|
MIT License
|
src/test/kotlin/be/ordina/duncan/casteleyn/github/actions/GitHubActionsApplicationTests.kt
|
JessicaBraekman
| 501,334,630 | false | null |
package be.ordina.duncan.casteleyn.github.actions
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class GitHubActionsApplicationTests {
@Test
fun contextLoads() {
// Tests if our context actually starts
}
}
| 0 |
Kotlin
|
0
| 0 |
093d72d7a9af9afb44cd93c2b82e0b2c060d04a2
| 293 |
Demo
|
Apache License 2.0
|
androidApp/src/main/java/com/flepper/therapeutic/android/presentation/home/euti/EutiViewModel.kt
|
develNerd
| 526,878,724 | false |
{"Kotlin": 296821, "Ruby": 1782, "Swift": 345}
|
package com.flepper.therapeutic.android.presentation.home.euti
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.viewModelScope
import com.flepper.therapeutic.android.BuildConfig
import com.flepper.therapeutic.android.R
import com.flepper.therapeutic.android.di.ApplicationContext
import com.flepper.therapeutic.android.presentation.core.BaseViewModel
import com.flepper.therapeutic.android.presentation.theme.eventColors
import com.flepper.therapeutic.android.util.*
import com.flepper.therapeutic.data.*
import com.flepper.therapeutic.data.apppreference.AppPreference
import com.flepper.therapeutic.data.models.Filter
import com.flepper.therapeutic.data.models.WorldWideEvent
import com.flepper.therapeutic.data.models.appointments.*
import com.flepper.therapeutic.data.models.appointments.booking.AppointmentSegmentsItem
import com.flepper.therapeutic.data.models.appointments.booking.BookAppointmentResponse
import com.flepper.therapeutic.data.models.appointments.booking.Booking
import com.flepper.therapeutic.data.models.appointments.booking.BookingRequest
import com.flepper.therapeutic.data.models.customer.Customer
import com.flepper.therapeutic.data.models.customer.ReferenceId
import com.flepper.therapeutic.data.usecasefactories.AppointmentsUseCaseFactory
import com.flepper.therapeutic.data.usecasefactories.AuthUseCaseFactory
import com.flepper.therapeutic.data.usecasefactories.HomeUseCaseFactory
import com.prolificinteractive.materialcalendarview.CalendarDay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.koin.core.component.inject
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashSet
class EutiViewModel : BaseViewModel() {
val appPreferences: AppPreference by inject()
/** Get Whole Application Context -> PS this is okay to get in viewmodel since it doesn't relate to any view
* Might make testing difficult though bu we'll always find a way
* */
val applicationContext: ApplicationContext by inject()
private val homeUseCaseFactory: HomeUseCaseFactory by inject()
private val authUseCaseFactory: AuthUseCaseFactory by inject()
private val appointmentsUseCaseFactory: AppointmentsUseCaseFactory by inject()
/** @MainBottomSheetItems*/
/** Euti Replies*/
private val _eutiReplies = MutableStateFlow(
listOf<EutiChatType>(
EutiChatType.Euti("Hi there ${appPreferences.anonUser?.userName}", true),
EutiChatType.Euti("How can I help you today ?", false)
)
)
val eutiReplies: StateFlow<List<EutiChatType>> = _eutiReplies
private val _isChatLoading = MutableStateFlow(false)
val isChatLoading: StateFlow<Boolean> = _isChatLoading
fun setIsChatLoading(value: Boolean) {
_isChatLoading.value = value
}
private val _isChatAdded = MutableStateFlow(false)
val isChatAdded: StateFlow<Boolean>
get() = _isChatAdded
fun setIsChatAdded(value: Boolean) {
_isChatAdded.value = value
}
/** @AddReply*/
fun addToReplies(chatType: EutiChatType) {
var replies = mutableListOf<EutiChatType>()
replies = eutiReplies.value.toMutableList()
replies.add(chatType)
_eutiReplies.value = replies.toList()
setIsChatAdded(true)
}
/** @LogicTODetermineHead */
fun checkHead(eutiChatType: EutiChatType): Boolean {
when (eutiChatType) {
is EutiChatType.Euti -> {
return _eutiReplies.value.last() !is EutiChatType.Euti
}
is EutiChatType.Content -> {}
is EutiChatType.User -> {
return _eutiReplies.value.last() !is EutiChatType.User
}
}
return false
}
/** @GenericScreenTitle*/
private val _genericTitle = MutableStateFlow("")
val genericTitle: StateFlow<String>
get() = _genericTitle
fun setGenericTitle(value: String) {
_genericTitle.value = value
}
/** @GetEvents this logic exists in the homeviewModel, but we'll like that loading feature*/
private val _events = MutableStateFlow(OnResultObtained<List<WorldWideEvent>>(null, false))
val events: MutableStateFlow<OnResultObtained<List<WorldWideEvent>>>
get() = _events
/** @UpcomingEvts this logic exists in the homeviewModel, but we'll like that loading feature*/
private val _eventsUpcoming =
MutableStateFlow(OnResultObtained<List<WorldWideEvent>>(null, false))
val eventsUpcoming: MutableStateFlow<OnResultObtained<List<WorldWideEvent>>>
get() = _eventsUpcoming
/** TODO -> Also Write UseCse To Get Only Ongoing Events, Currently filtering because of time and events are not so much so that's alright */
fun getOnGoingEvents(isOngoing: Boolean) {
executeFirebaseUseCase(
viewModelScope = viewModelScope,
useCase = homeUseCaseFactory.getWorldEventsUseCase,
state = _events,
callback = { result ->
val backgroundColors = mutableListOf<Color>()
var currentColorIndex = 0
val eventResult = result.mapIndexed { index, worldWideEvent ->
if (backgroundColors.isEmpty()) {
backgroundColors.addAll(eventColors)
}
val itemColor = backgroundColors[currentColorIndex]
if (backgroundColors.contains(itemColor)) {
backgroundColors.remove(itemColor)
}
worldWideEvent.backGroundColor = itemColor
if (currentColorIndex < backgroundColors.size - 1) currentColorIndex++ else currentColorIndex =
0
worldWideEvent
}
Log.e("Result", eventResult.toString())
/** Assuming on Going events */
val eutiListReply =
if (eventResult.isEmpty()) applicationContext().getString(R.string.events_not_available) else applicationContext().getString(
R.string.response_to_found_events
)
val eutiOnGoingEventReply =
if (eventResult.isEmpty()) applicationContext().getString(R.string.events_not_available) else applicationContext().getString(
R.string.response_to_ongoing_event,
eventResult.firstOrNull()?.hashTag ?: ""
)
val eutiReplyText = if (!isOngoing) eutiListReply else eutiOnGoingEventReply
addToReplies(
EutiChatType.Euti(eutiReplyText, true).apply { this.isHead = checkHead(this) })
addToReplies(
EutiChatType.Content(
_currentEutiType.value.id,
eventResult.filter { if (isOngoing) it.isOngoing else !it.isOngoing },
listOf(),
_currentEutiType.value.sheetContentType
)
)
setIsChatLoading(false)
}, onError = {
//assign to error variable
})
}
/** Current OptionBottom Id ]*/
private val _currentOptionID = MutableStateFlow("")
val currentOptionID: StateFlow<String>
get() = _currentOptionID
fun setOptionBottomId(value: String) {
_currentOptionID.value = value
}
/** @CurrenEutiType*/
private val _currentEutiType = MutableStateFlow(
EutiChatType.Content(
"", listOf(),
emptyList(), SheetContentType.DEFAULT
)
)
val currentEutiType: StateFlow<EutiChatType>
get() = _currentEutiType
fun setCurrentEutiType(value: EutiChatType) {
_currentEutiType.value = value as EutiChatType.Content
}
/** @SignInOrLogin - To book a session*/
enum class SignInMethod {
SIGN_IN,
SIGN_UP
}
var signInMethod = SignInMethod.SIGN_UP
/** @SignIn*/
private val _signUpResponse =
MutableStateFlow(OnResultObtained<CurrentUser>(null, false))
val signUpResponse: StateFlow<OnResultObtained<CurrentUser>>
get() = _signUpResponse
fun signUpUser(email: String, password: String) {
_signUpResponse.value = OnResultObtained(null, false)
val signUpRequest =
SignUpRequest(appPreferences.anonUser?.userName ?: "Anon", email, password)
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = signUpRequest,
useCase = authUseCaseFactory.signUpUseCase,
state = _signUpResponse,
callback = { result ->
Log.e("Result", result.toString())
getCustomer(result.id, result, SignInMethod.SIGN_UP)
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @SignIn */
private val _signInResponse =
MutableStateFlow(OnResultObtained<CurrentUser>(null, false))
val signInResponse: StateFlow<OnResultObtained<CurrentUser>>
get() = _signInResponse
fun signInUser(email: String, password: String) {
_signInResponse.value = OnResultObtained(null, false)
val signInRequest =
SignInRequest(email, password)
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = signInRequest,
useCase = authUseCaseFactory.signInUseCase,
state = _signInResponse,
callback = { result ->
Log.e("Result", result.toString())
_signInResponse.value = OnResultObtained(result, true)
appPreferences.signInUser = result
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
fun signInWithGoogle(idToken: String) {
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = idToken,
useCase = authUseCaseFactory.signInWithGoogleUseCase,
state = _signInResponse,
callback = { result ->
Log.e("Result", result.toString())
// _signInResponse.value = OnResultObtained(result, true)
getCustomer(result.id, result, SignInMethod.SIGN_IN)
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @GetCustomer*/
/** Get Customer if customer does not exist and return if exists */
private fun getCustomer(
referenceId: String,
signInResult: CurrentUser,
signInMethod: SignInMethod
) {
val request = Filter(referenceId = ReferenceId(referenceId))
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getCustomerUseCase,
inputValue = request,
callback = { resultList ->
val result = resultList.first()
Log.e("Result-Cust", result.toString())
if (signInMethod == SignInMethod.SIGN_IN) {
_signInResponse.value = OnResultObtained(
signInResult.apply { squareCustomerID = result.customer_id },
true
)
appPreferences.signInUser = signInResult.apply { squareCustomerID = result.customer_id }
} else {
_signUpResponse.value = OnResultObtained(signInResult, true)
appPreferences.signInUser = signInResult.apply { squareCustomerID = result.customer_id }
}
},
onError = {
/** Create if customer does not exist*/
createCustomer(referenceId, signInResult, signInMethod)
Log.e("Result", it.message.toString())
})
}
/** @CreateCustomer */
fun createCustomer(referenceId: String, signInResult: CurrentUser, signInMethod: SignInMethod) {
val request = Customer(
signInResult.email,
referenceId,
COMPANY_NAME,
DEFAULT_NOTE,
appPreferences.anonUser?.userName ?: "",
appPreferences.anonUser?.userName ?: "",
COMPANY_PHONE_NUMBER
)
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.createCustomerUseCase,
inputValue = request,
callback = { result ->
if (signInMethod == SignInMethod.SIGN_IN) {
_signInResponse.value = OnResultObtained(
signInResult.apply { squareCustomerID = result.customer_id },
true
)
appPreferences.signInUser = signInResult
} else {
_signUpResponse.value = OnResultObtained(signInResult.apply { squareCustomerID = result.customer_id }, true)
appPreferences.signInUser = signInResult.apply {
Log.e("ResultFor",result.toString())
squareCustomerID = result.customer_id
Log.e("ResultSquareCustomer ID",squareCustomerID)
}
}
},
onError = {
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
Log.e("Result", it.message.toString())
})
}
/** @SignInError*/
private val _eutiGenericError = MutableStateFlow("")
val eutiGenericError: StateFlow<String>
get() = _eutiGenericError
fun setSignInError(value: String) {
_eutiGenericError.value = value
}
/** @SetAppointmentDate*/
private val _selectedAppointmentDate = MutableStateFlow(CalendarDay.today())
val selectedAppointmentDate: StateFlow<CalendarDay>
get() = _selectedAppointmentDate
fun setAppointmentDate(value: CalendarDay) {
_selectedAppointmentDate.value = value
}
/** @AvailableDates Local*/
fun getAvailableDates(): HashSet<CalendarDay> {
val availableDates = mutableSetOf<CalendarDay>()
val startCal = Calendar.getInstance()
var start = startCal.get(Calendar.DATE)
startCal.set(Calendar.DATE, startCal.get(Calendar.DATE).plus(7))
val lastIndex = startCal.get(Calendar.DATE)
var isEndOfMonth = false
if (start > lastIndex){
isEndOfMonth = true
availableDates.add(Calendar.getInstance().toCalendarDay())
start = 1
}
Log.e("Start-last", "$start + $lastIndex")
(start..lastIndex).forEach { day ->
val c1 = if (!isEndOfMonth) Calendar.getInstance() else Calendar.getInstance().apply { this.set(Calendar.MONTH,this.get(Calendar.MONTH) + 1) }
c1.set(Calendar.DATE, day)
availableDates.add(c1.toCalendarDay())
}
return availableDates.toHashSet()
}
/** @GetAvailableTimes Server*/
fun getTeamMembersAvailableTime() {
executeLocalFlowUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getTeamMembersLocalUseCase,
inputValue = Unit,
callback = { result ->
Log.e("Result-Success", result.toString())
val startAt =
_selectedAppointmentDate.value.toAppointmentStartCalendar().time.asSquareApiDateString()
val endAt =
_selectedAppointmentDate.value.toAppointmentEndCalendar().time.asSquareApiDateString()
val startAtRange = StartAtRange(startAt = startAt, endAt = endAt)
getAvailableTimes(startAtRange, result.map { it.id })
}, onError = {
//assign to error variable
it.printStackTrace()
Log.e("Error", it.toString())
})
}
val teamMemberTimeAndIdPair: MutableMap<String, String> = mutableMapOf()
private fun getAvailableTimes(
startAtRange: StartAtRange,
teamMemberIds: List<String>
) {
val segmentFilters = SegmentFiltersItem(
serviceVariationId = BuildConfig.THERAPY_SESSION_CATALOG_ITEM_ID,
teamMemberIdFilter = TeamMemberIdFilter(teamMemberIds)
)
val appointmentsFilter = AppointmentsFilter(
bookingId = "",
startAtRange,
listOf(segmentFilters),
locationId = BuildConfig.DEFAULT_TEST_LOCATION_ID
)
val request = SearchAvailabilityRequest(AvailabilityQuery(appointmentsFilter))
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getAvailableTimeUseCase,
inputValue = request,
callback = { availableTimes ->
val availableTimePair: MutableMap<String, String> = mutableMapOf()
availableTimes.forEach { availableTime ->
val hourMinuteFormat = SimpleDateFormat(
"hh:mm a",
Locale.getDefault()
)
val cal = Calendar.getInstance()
cal.timeInMillis = availableTime.convertStartToUserTimeZone()
/** Filter for if minute is 30*/
if (cal.get(Calendar.MINUTE) != 30) {
val c1 = availableTime.startAt.convertUTCTimeToSystemDefault()
val end = availableTime.startAt.convertUTCTimeToSystemDefault()
// set duration for end
end.set(
Calendar.MINUTE,
availableTime.appointmentSegments?.first()?.durationMinutes ?: 45
)
val c2 = end
availableTimePair[hourMinuteFormat.format(c1.time)] =
hourMinuteFormat.format(c2.time)
teamMemberTimeAndIdPair[hourMinuteFormat.format(c1.time)] =
availableTime.appointmentSegments?.first()?.teamMemberId ?: ""
}
}
_appointmentTimes.value = availableTimePair
selectedAppointmentDate.value.apply {
val eutiChat = EutiChatType.Euti(applicationContext().getString(R.string.select_appointment_time,"$year-$month-$day"), false).apply {
this.isHead = checkHead(this)
}
addToReplies(eutiChat)
}
setIsChatLoading(false)
},
onError = {
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @AvailableTimes*/
private val _appointmentTimes = MutableStateFlow(mapOf<String, String>())
val appointmentTimes: StateFlow<Map<String, String>>
get() = _appointmentTimes
/** Not in use anymore*/
fun getAvailableTimesLocalTest() {
val availableTimePair: MutableMap<String, String> = mutableMapOf()
val dateFormat = SimpleDateFormat(
"hh:mm a",
Locale.getDefault()
)
try {
(8..17).forEach { start ->
val c1 = Calendar.getInstance()
val timeOfDay = if (start < 12) "am" else "pm"
c1.time = dateFormat.parse("$start:00 $timeOfDay")!!
val c2 = Calendar.getInstance()
c2.time = dateFormat.parse("$start:45 $timeOfDay")!!
availableTimePair[dateFormat.format(c1.time)] = dateFormat.format(c2.time)
}
} catch (e: Exception) {
Log.e("", "")
}
_appointmentTimes.value = availableTimePair
}
/** @SelectedAppointmentTime*/
private var selectedTeamberId = ""
private val _selectedAppointmentTime = MutableStateFlow("")
val selectedAppointmentTime: MutableStateFlow<String>
get() = _selectedAppointmentTime
fun setSelectedAppointmentTime(value: String) {
_selectedAppointmentTime.value = value
}
/** @BookAppointment Finally Book an Appointment*/
fun bookAppointment() {
val timeKey = _selectedAppointmentTime.value.split("-").first().toString().trim()
/** timekey is expected to be 8:00 am*/
val startAt = toSquareApiStartAt(_selectedAppointmentDate.value, timeKey)
Log.e("StartAt",startAt)
val teamMemberId = teamMemberTimeAndIdPair[timeKey]
val appointmentSegment = AppointmentSegmentsItem(
DEFAULT_SESSION_DURATION,
teamMemberId ?: "",
DEFAULT_SERVICE_VERSION,
BuildConfig.THERAPY_SESSION_CATALOG_ITEM_ID
)
val booking = Booking(
listOf(appointmentSegment),
DEFAULT_CUSTOMER_NOTE,
appPreferences.signInUser?.squareCustomerID ?: "",
startAt,
DEFAULT_LOCATION_TYPE,
BuildConfig.DEFAULT_TEST_LOCATION_ID
)
val request = BookingRequest(booking)
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.bookAppointmentUseCase,
inputValue = request,
callback = { result ->
setIsChatLoading(false)
saveBookingLocal(result)
addToReplies(EutiChatType.Euti(applicationContext().getString(R.string.yay_booked),false).apply {
isHead = checkHead(this)
})
},
onError = {
setIsChatLoading(false)
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
addToReplies(EutiChatType.Euti(applicationContext().getString(R.string.euti_sorry_something_went_wrong),false).apply {
isHead = checkHead(this)
})
})
}
/** @SaveBookingLocal*/
private val _bookingSuccess = MutableStateFlow(false)
val bookingSuccess: MutableStateFlow<Boolean>
get() = _bookingSuccess
fun setBookingFailed(){
_bookingSuccess.value = false
}
fun saveBookingLocal(request: BookAppointmentResponse){
executeLocalUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.saveBookingLocal,
inputValue = request,
callback = { result ->
Log.e("Result-Success", "Yay")
_bookingSuccess.value = true
addToReplies(EutiChatType.Content(UUID.randomUUID().toString(),
listOf(), listOf(request),SheetContentType.SCHEDULE_SESSION))
}, onError = {
//assign to error variable
setBookingFailed()
it.printStackTrace()
Log.e("Error", it.toString())
})
}
private fun toSquareApiStartAt(calendarDay: CalendarDay, startTime: String): String {
val startAtCal = Calendar.getInstance()
startAtCal.set(Calendar.YEAR, calendarDay.year)
startAtCal.set(Calendar.MONTH, calendarDay.month - 1)
startAtCal.set(Calendar.DATE, calendarDay.day)
val pm = startTime.split(" ")[1].trim().lowercase()
startAtCal.set(Calendar.AM_PM,if (pm.contains(pm)) Calendar.PM else Calendar.AM)
startAtCal.set(Calendar.HOUR, startTime.split(":").first().trim().toInt())
//
startAtCal.set(Calendar.MINUTE, 0)
startAtCal.set(Calendar.SECOND, 0)
startAtCal.set(Calendar.MILLISECOND, 0)
val sourceFormat = SimpleDateFormat(SQUARE_API_DATE_FORMAT, Locale.getDefault())
return sourceFormat.format(startAtCal.time) // => Date is in UTC now, which is default business time
}
}
| 0 |
Kotlin
|
0
| 1 |
e2b1e12e9fef20a89c96b72b18cd6ab613c16af3
| 24,523 |
Therapeutic
|
Apache License 2.0
|
androidApp/src/main/java/com/flepper/therapeutic/android/presentation/home/euti/EutiViewModel.kt
|
develNerd
| 526,878,724 | false |
{"Kotlin": 296821, "Ruby": 1782, "Swift": 345}
|
package com.flepper.therapeutic.android.presentation.home.euti
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.viewModelScope
import com.flepper.therapeutic.android.BuildConfig
import com.flepper.therapeutic.android.R
import com.flepper.therapeutic.android.di.ApplicationContext
import com.flepper.therapeutic.android.presentation.core.BaseViewModel
import com.flepper.therapeutic.android.presentation.theme.eventColors
import com.flepper.therapeutic.android.util.*
import com.flepper.therapeutic.data.*
import com.flepper.therapeutic.data.apppreference.AppPreference
import com.flepper.therapeutic.data.models.Filter
import com.flepper.therapeutic.data.models.WorldWideEvent
import com.flepper.therapeutic.data.models.appointments.*
import com.flepper.therapeutic.data.models.appointments.booking.AppointmentSegmentsItem
import com.flepper.therapeutic.data.models.appointments.booking.BookAppointmentResponse
import com.flepper.therapeutic.data.models.appointments.booking.Booking
import com.flepper.therapeutic.data.models.appointments.booking.BookingRequest
import com.flepper.therapeutic.data.models.customer.Customer
import com.flepper.therapeutic.data.models.customer.ReferenceId
import com.flepper.therapeutic.data.usecasefactories.AppointmentsUseCaseFactory
import com.flepper.therapeutic.data.usecasefactories.AuthUseCaseFactory
import com.flepper.therapeutic.data.usecasefactories.HomeUseCaseFactory
import com.prolificinteractive.materialcalendarview.CalendarDay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.koin.core.component.inject
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashSet
class EutiViewModel : BaseViewModel() {
val appPreferences: AppPreference by inject()
/** Get Whole Application Context -> PS this is okay to get in viewmodel since it doesn't relate to any view
* Might make testing difficult though bu we'll always find a way
* */
val applicationContext: ApplicationContext by inject()
private val homeUseCaseFactory: HomeUseCaseFactory by inject()
private val authUseCaseFactory: AuthUseCaseFactory by inject()
private val appointmentsUseCaseFactory: AppointmentsUseCaseFactory by inject()
/** @MainBottomSheetItems*/
/** Euti Replies*/
private val _eutiReplies = MutableStateFlow(
listOf<EutiChatType>(
EutiChatType.Euti("Hi there ${appPreferences.anonUser?.userName}", true),
EutiChatType.Euti("How can I help you today ?", false)
)
)
val eutiReplies: StateFlow<List<EutiChatType>> = _eutiReplies
private val _isChatLoading = MutableStateFlow(false)
val isChatLoading: StateFlow<Boolean> = _isChatLoading
fun setIsChatLoading(value: Boolean) {
_isChatLoading.value = value
}
private val _isChatAdded = MutableStateFlow(false)
val isChatAdded: StateFlow<Boolean>
get() = _isChatAdded
fun setIsChatAdded(value: Boolean) {
_isChatAdded.value = value
}
/** @AddReply*/
fun addToReplies(chatType: EutiChatType) {
var replies = mutableListOf<EutiChatType>()
replies = eutiReplies.value.toMutableList()
replies.add(chatType)
_eutiReplies.value = replies.toList()
setIsChatAdded(true)
}
/** @LogicTODetermineHead */
fun checkHead(eutiChatType: EutiChatType): Boolean {
when (eutiChatType) {
is EutiChatType.Euti -> {
return _eutiReplies.value.last() !is EutiChatType.Euti
}
is EutiChatType.Content -> {}
is EutiChatType.User -> {
return _eutiReplies.value.last() !is EutiChatType.User
}
}
return false
}
/** @GenericScreenTitle*/
private val _genericTitle = MutableStateFlow("")
val genericTitle: StateFlow<String>
get() = _genericTitle
fun setGenericTitle(value: String) {
_genericTitle.value = value
}
/** @GetEvents this logic exists in the homeviewModel, but we'll like that loading feature*/
private val _events = MutableStateFlow(OnResultObtained<List<WorldWideEvent>>(null, false))
val events: MutableStateFlow<OnResultObtained<List<WorldWideEvent>>>
get() = _events
/** @UpcomingEvts this logic exists in the homeviewModel, but we'll like that loading feature*/
private val _eventsUpcoming =
MutableStateFlow(OnResultObtained<List<WorldWideEvent>>(null, false))
val eventsUpcoming: MutableStateFlow<OnResultObtained<List<WorldWideEvent>>>
get() = _eventsUpcoming
/** TODO -> Also Write UseCse To Get Only Ongoing Events, Currently filtering because of time and events are not so much so that's alright */
fun getOnGoingEvents(isOngoing: Boolean) {
executeFirebaseUseCase(
viewModelScope = viewModelScope,
useCase = homeUseCaseFactory.getWorldEventsUseCase,
state = _events,
callback = { result ->
val backgroundColors = mutableListOf<Color>()
var currentColorIndex = 0
val eventResult = result.mapIndexed { index, worldWideEvent ->
if (backgroundColors.isEmpty()) {
backgroundColors.addAll(eventColors)
}
val itemColor = backgroundColors[currentColorIndex]
if (backgroundColors.contains(itemColor)) {
backgroundColors.remove(itemColor)
}
worldWideEvent.backGroundColor = itemColor
if (currentColorIndex < backgroundColors.size - 1) currentColorIndex++ else currentColorIndex =
0
worldWideEvent
}
Log.e("Result", eventResult.toString())
/** Assuming on Going events */
val eutiListReply =
if (eventResult.isEmpty()) applicationContext().getString(R.string.events_not_available) else applicationContext().getString(
R.string.response_to_found_events
)
val eutiOnGoingEventReply =
if (eventResult.isEmpty()) applicationContext().getString(R.string.events_not_available) else applicationContext().getString(
R.string.response_to_ongoing_event,
eventResult.firstOrNull()?.hashTag ?: ""
)
val eutiReplyText = if (!isOngoing) eutiListReply else eutiOnGoingEventReply
addToReplies(
EutiChatType.Euti(eutiReplyText, true).apply { this.isHead = checkHead(this) })
addToReplies(
EutiChatType.Content(
_currentEutiType.value.id,
eventResult.filter { if (isOngoing) it.isOngoing else !it.isOngoing },
listOf(),
_currentEutiType.value.sheetContentType
)
)
setIsChatLoading(false)
}, onError = {
//assign to error variable
})
}
/** Current OptionBottom Id ]*/
private val _currentOptionID = MutableStateFlow("")
val currentOptionID: StateFlow<String>
get() = _currentOptionID
fun setOptionBottomId(value: String) {
_currentOptionID.value = value
}
/** @CurrenEutiType*/
private val _currentEutiType = MutableStateFlow(
EutiChatType.Content(
"", listOf(),
emptyList(), SheetContentType.DEFAULT
)
)
val currentEutiType: StateFlow<EutiChatType>
get() = _currentEutiType
fun setCurrentEutiType(value: EutiChatType) {
_currentEutiType.value = value as EutiChatType.Content
}
/** @SignInOrLogin - To book a session*/
enum class SignInMethod {
SIGN_IN,
SIGN_UP
}
var signInMethod = SignInMethod.SIGN_UP
/** @SignIn*/
private val _signUpResponse =
MutableStateFlow(OnResultObtained<CurrentUser>(null, false))
val signUpResponse: StateFlow<OnResultObtained<CurrentUser>>
get() = _signUpResponse
fun signUpUser(email: String, password: String) {
_signUpResponse.value = OnResultObtained(null, false)
val signUpRequest =
SignUpRequest(appPreferences.anonUser?.userName ?: "Anon", email, password)
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = signUpRequest,
useCase = authUseCaseFactory.signUpUseCase,
state = _signUpResponse,
callback = { result ->
Log.e("Result", result.toString())
getCustomer(result.id, result, SignInMethod.SIGN_UP)
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @SignIn */
private val _signInResponse =
MutableStateFlow(OnResultObtained<CurrentUser>(null, false))
val signInResponse: StateFlow<OnResultObtained<CurrentUser>>
get() = _signInResponse
fun signInUser(email: String, password: String) {
_signInResponse.value = OnResultObtained(null, false)
val signInRequest =
SignInRequest(email, password)
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = signInRequest,
useCase = authUseCaseFactory.signInUseCase,
state = _signInResponse,
callback = { result ->
Log.e("Result", result.toString())
_signInResponse.value = OnResultObtained(result, true)
appPreferences.signInUser = result
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
fun signInWithGoogle(idToken: String) {
executeFirebaseUseCase(
viewModelScope = viewModelScope,
inputValue = idToken,
useCase = authUseCaseFactory.signInWithGoogleUseCase,
state = _signInResponse,
callback = { result ->
Log.e("Result", result.toString())
// _signInResponse.value = OnResultObtained(result, true)
getCustomer(result.id, result, SignInMethod.SIGN_IN)
}, onError = {
//assign to error variable
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @GetCustomer*/
/** Get Customer if customer does not exist and return if exists */
private fun getCustomer(
referenceId: String,
signInResult: CurrentUser,
signInMethod: SignInMethod
) {
val request = Filter(referenceId = ReferenceId(referenceId))
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getCustomerUseCase,
inputValue = request,
callback = { resultList ->
val result = resultList.first()
Log.e("Result-Cust", result.toString())
if (signInMethod == SignInMethod.SIGN_IN) {
_signInResponse.value = OnResultObtained(
signInResult.apply { squareCustomerID = result.customer_id },
true
)
appPreferences.signInUser = signInResult.apply { squareCustomerID = result.customer_id }
} else {
_signUpResponse.value = OnResultObtained(signInResult, true)
appPreferences.signInUser = signInResult.apply { squareCustomerID = result.customer_id }
}
},
onError = {
/** Create if customer does not exist*/
createCustomer(referenceId, signInResult, signInMethod)
Log.e("Result", it.message.toString())
})
}
/** @CreateCustomer */
fun createCustomer(referenceId: String, signInResult: CurrentUser, signInMethod: SignInMethod) {
val request = Customer(
signInResult.email,
referenceId,
COMPANY_NAME,
DEFAULT_NOTE,
appPreferences.anonUser?.userName ?: "",
appPreferences.anonUser?.userName ?: "",
COMPANY_PHONE_NUMBER
)
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.createCustomerUseCase,
inputValue = request,
callback = { result ->
if (signInMethod == SignInMethod.SIGN_IN) {
_signInResponse.value = OnResultObtained(
signInResult.apply { squareCustomerID = result.customer_id },
true
)
appPreferences.signInUser = signInResult
} else {
_signUpResponse.value = OnResultObtained(signInResult.apply { squareCustomerID = result.customer_id }, true)
appPreferences.signInUser = signInResult.apply {
Log.e("ResultFor",result.toString())
squareCustomerID = result.customer_id
Log.e("ResultSquareCustomer ID",squareCustomerID)
}
}
},
onError = {
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
Log.e("Result", it.message.toString())
})
}
/** @SignInError*/
private val _eutiGenericError = MutableStateFlow("")
val eutiGenericError: StateFlow<String>
get() = _eutiGenericError
fun setSignInError(value: String) {
_eutiGenericError.value = value
}
/** @SetAppointmentDate*/
private val _selectedAppointmentDate = MutableStateFlow(CalendarDay.today())
val selectedAppointmentDate: StateFlow<CalendarDay>
get() = _selectedAppointmentDate
fun setAppointmentDate(value: CalendarDay) {
_selectedAppointmentDate.value = value
}
/** @AvailableDates Local*/
fun getAvailableDates(): HashSet<CalendarDay> {
val availableDates = mutableSetOf<CalendarDay>()
val startCal = Calendar.getInstance()
var start = startCal.get(Calendar.DATE)
startCal.set(Calendar.DATE, startCal.get(Calendar.DATE).plus(7))
val lastIndex = startCal.get(Calendar.DATE)
var isEndOfMonth = false
if (start > lastIndex){
isEndOfMonth = true
availableDates.add(Calendar.getInstance().toCalendarDay())
start = 1
}
Log.e("Start-last", "$start + $lastIndex")
(start..lastIndex).forEach { day ->
val c1 = if (!isEndOfMonth) Calendar.getInstance() else Calendar.getInstance().apply { this.set(Calendar.MONTH,this.get(Calendar.MONTH) + 1) }
c1.set(Calendar.DATE, day)
availableDates.add(c1.toCalendarDay())
}
return availableDates.toHashSet()
}
/** @GetAvailableTimes Server*/
fun getTeamMembersAvailableTime() {
executeLocalFlowUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getTeamMembersLocalUseCase,
inputValue = Unit,
callback = { result ->
Log.e("Result-Success", result.toString())
val startAt =
_selectedAppointmentDate.value.toAppointmentStartCalendar().time.asSquareApiDateString()
val endAt =
_selectedAppointmentDate.value.toAppointmentEndCalendar().time.asSquareApiDateString()
val startAtRange = StartAtRange(startAt = startAt, endAt = endAt)
getAvailableTimes(startAtRange, result.map { it.id })
}, onError = {
//assign to error variable
it.printStackTrace()
Log.e("Error", it.toString())
})
}
val teamMemberTimeAndIdPair: MutableMap<String, String> = mutableMapOf()
private fun getAvailableTimes(
startAtRange: StartAtRange,
teamMemberIds: List<String>
) {
val segmentFilters = SegmentFiltersItem(
serviceVariationId = BuildConfig.THERAPY_SESSION_CATALOG_ITEM_ID,
teamMemberIdFilter = TeamMemberIdFilter(teamMemberIds)
)
val appointmentsFilter = AppointmentsFilter(
bookingId = "",
startAtRange,
listOf(segmentFilters),
locationId = BuildConfig.DEFAULT_TEST_LOCATION_ID
)
val request = SearchAvailabilityRequest(AvailabilityQuery(appointmentsFilter))
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.getAvailableTimeUseCase,
inputValue = request,
callback = { availableTimes ->
val availableTimePair: MutableMap<String, String> = mutableMapOf()
availableTimes.forEach { availableTime ->
val hourMinuteFormat = SimpleDateFormat(
"hh:mm a",
Locale.getDefault()
)
val cal = Calendar.getInstance()
cal.timeInMillis = availableTime.convertStartToUserTimeZone()
/** Filter for if minute is 30*/
if (cal.get(Calendar.MINUTE) != 30) {
val c1 = availableTime.startAt.convertUTCTimeToSystemDefault()
val end = availableTime.startAt.convertUTCTimeToSystemDefault()
// set duration for end
end.set(
Calendar.MINUTE,
availableTime.appointmentSegments?.first()?.durationMinutes ?: 45
)
val c2 = end
availableTimePair[hourMinuteFormat.format(c1.time)] =
hourMinuteFormat.format(c2.time)
teamMemberTimeAndIdPair[hourMinuteFormat.format(c1.time)] =
availableTime.appointmentSegments?.first()?.teamMemberId ?: ""
}
}
_appointmentTimes.value = availableTimePair
selectedAppointmentDate.value.apply {
val eutiChat = EutiChatType.Euti(applicationContext().getString(R.string.select_appointment_time,"$year-$month-$day"), false).apply {
this.isHead = checkHead(this)
}
addToReplies(eutiChat)
}
setIsChatLoading(false)
},
onError = {
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
})
}
/** @AvailableTimes*/
private val _appointmentTimes = MutableStateFlow(mapOf<String, String>())
val appointmentTimes: StateFlow<Map<String, String>>
get() = _appointmentTimes
/** Not in use anymore*/
fun getAvailableTimesLocalTest() {
val availableTimePair: MutableMap<String, String> = mutableMapOf()
val dateFormat = SimpleDateFormat(
"hh:mm a",
Locale.getDefault()
)
try {
(8..17).forEach { start ->
val c1 = Calendar.getInstance()
val timeOfDay = if (start < 12) "am" else "pm"
c1.time = dateFormat.parse("$start:00 $timeOfDay")!!
val c2 = Calendar.getInstance()
c2.time = dateFormat.parse("$start:45 $timeOfDay")!!
availableTimePair[dateFormat.format(c1.time)] = dateFormat.format(c2.time)
}
} catch (e: Exception) {
Log.e("", "")
}
_appointmentTimes.value = availableTimePair
}
/** @SelectedAppointmentTime*/
private var selectedTeamberId = ""
private val _selectedAppointmentTime = MutableStateFlow("")
val selectedAppointmentTime: MutableStateFlow<String>
get() = _selectedAppointmentTime
fun setSelectedAppointmentTime(value: String) {
_selectedAppointmentTime.value = value
}
/** @BookAppointment Finally Book an Appointment*/
fun bookAppointment() {
val timeKey = _selectedAppointmentTime.value.split("-").first().toString().trim()
/** timekey is expected to be 8:00 am*/
val startAt = toSquareApiStartAt(_selectedAppointmentDate.value, timeKey)
Log.e("StartAt",startAt)
val teamMemberId = teamMemberTimeAndIdPair[timeKey]
val appointmentSegment = AppointmentSegmentsItem(
DEFAULT_SESSION_DURATION,
teamMemberId ?: "",
DEFAULT_SERVICE_VERSION,
BuildConfig.THERAPY_SESSION_CATALOG_ITEM_ID
)
val booking = Booking(
listOf(appointmentSegment),
DEFAULT_CUSTOMER_NOTE,
appPreferences.signInUser?.squareCustomerID ?: "",
startAt,
DEFAULT_LOCATION_TYPE,
BuildConfig.DEFAULT_TEST_LOCATION_ID
)
val request = BookingRequest(booking)
executeApiCallUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.bookAppointmentUseCase,
inputValue = request,
callback = { result ->
setIsChatLoading(false)
saveBookingLocal(result)
addToReplies(EutiChatType.Euti(applicationContext().getString(R.string.yay_booked),false).apply {
isHead = checkHead(this)
})
},
onError = {
setIsChatLoading(false)
_eutiGenericError.value =
applicationContext().getString(R.string.something_went_wrong)
addToReplies(EutiChatType.Euti(applicationContext().getString(R.string.euti_sorry_something_went_wrong),false).apply {
isHead = checkHead(this)
})
})
}
/** @SaveBookingLocal*/
private val _bookingSuccess = MutableStateFlow(false)
val bookingSuccess: MutableStateFlow<Boolean>
get() = _bookingSuccess
fun setBookingFailed(){
_bookingSuccess.value = false
}
fun saveBookingLocal(request: BookAppointmentResponse){
executeLocalUseCase(
viewModelScope = viewModelScope,
useCase = appointmentsUseCaseFactory.saveBookingLocal,
inputValue = request,
callback = { result ->
Log.e("Result-Success", "Yay")
_bookingSuccess.value = true
addToReplies(EutiChatType.Content(UUID.randomUUID().toString(),
listOf(), listOf(request),SheetContentType.SCHEDULE_SESSION))
}, onError = {
//assign to error variable
setBookingFailed()
it.printStackTrace()
Log.e("Error", it.toString())
})
}
private fun toSquareApiStartAt(calendarDay: CalendarDay, startTime: String): String {
val startAtCal = Calendar.getInstance()
startAtCal.set(Calendar.YEAR, calendarDay.year)
startAtCal.set(Calendar.MONTH, calendarDay.month - 1)
startAtCal.set(Calendar.DATE, calendarDay.day)
val pm = startTime.split(" ")[1].trim().lowercase()
startAtCal.set(Calendar.AM_PM,if (pm.contains(pm)) Calendar.PM else Calendar.AM)
startAtCal.set(Calendar.HOUR, startTime.split(":").first().trim().toInt())
//
startAtCal.set(Calendar.MINUTE, 0)
startAtCal.set(Calendar.SECOND, 0)
startAtCal.set(Calendar.MILLISECOND, 0)
val sourceFormat = SimpleDateFormat(SQUARE_API_DATE_FORMAT, Locale.getDefault())
return sourceFormat.format(startAtCal.time) // => Date is in UTC now, which is default business time
}
}
| 0 |
Kotlin
|
0
| 1 |
e2b1e12e9fef20a89c96b72b18cd6ab613c16af3
| 24,523 |
Therapeutic
|
Apache License 2.0
|
app/src/main/java/com/funnydevs/conductor_lifecycle/sample/TestController.kt
|
FunnyDevs
| 244,743,221 | false | null |
package com.funnydevs.conductor_lifecycle.sample
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import com.funnydevs.annotations.OnAttach
import com.funnydevs.annotations.OnDetach
class TestController : Controller() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
val view: View =
inflater.inflate(R.layout.test, container, false)
return view
}
@OnAttach
private fun start(){
Log.d("start","ok")
}
@OnDetach
private fun stop(){
Log.d("stop","ok")
}
}
| 0 |
Kotlin
|
0
| 0 |
e24faca32c0a994e84c833d64359f115192cc998
| 686 |
Conductor-lifecycle
|
Apache License 2.0
|
frogocoreconsumeapi/src/main/java/com/frogobox/coreapi/movie/model/MovieReviewResult.kt
|
frogobox
| 389,577,716 | false | null |
package com.frogobox.coreapi.movie.model
data class MovieReviewResult(
val author: String? = null,
val content: String? = null,
val id: String? = null,
val url: String? = null
)
| 0 |
Kotlin
|
2
| 7 |
1dd90a037f9acb2ba30066f753d35f7b909621a6
| 194 |
frogo-consume-api
|
Apache License 2.0
|
app/src/main/java/com/codepath/sadab/parstagram/PostAdapter.kt
|
Proto007
| 469,212,037 | false | null |
package com.codepath.sadab.parstagram
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class PostAdapter(val context: Context,val posts:MutableList<Post>):RecyclerView.Adapter<PostAdapter.ViewHolder> (){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostAdapter.ViewHolder {
val view=LayoutInflater.from(context).inflate(R.layout.item_post,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: PostAdapter.ViewHolder, position: Int) {
val post=posts.get(position)
holder.bind(post)
}
override fun getItemCount(): Int {
return posts.size
}
// Clean all elements of the recycler
fun clear() {
posts.clear()
notifyDataSetChanged()
}
// Add a list of items -- change to type used
fun addAll(postList: List<Post>) {
posts.addAll(postList)
notifyDataSetChanged()
}
class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
val tvUsername:TextView
val ivImage:ImageView
val tvDescription:TextView
init{
tvUsername=itemView.findViewById(R.id.tvUserName)
ivImage=itemView.findViewById(R.id.ivImage)
tvDescription=itemView.findViewById(R.id.tvDescription)
}
fun bind(post:Post){
tvDescription.text=post.getDescription()
tvUsername.text=post.getUser()?.username
Glide.with(itemView.context).load(post.getImage()?.url).into(ivImage)
}
}
}
| 2 |
Kotlin
|
0
| 0 |
0ad65c70908d4660d6424c502966600fc664f3a8
| 1,816 |
Codepath-Parstagram
|
MIT License
|
uranium-swing/src/main/kotlin/pl/karol202/uranium/swing/layout/grid/SwingGridLayout.kt
|
karol-202
| 269,320,433 | false | null |
package pl.karol202.uranium.swing.layout.grid
import pl.karol202.uranium.core.common.AutoKey
import pl.karol202.uranium.core.common.UProps
import pl.karol202.uranium.core.element.component
import pl.karol202.uranium.core.render.URenderScope
import pl.karol202.uranium.swing.*
import pl.karol202.uranium.swing.Builder
import pl.karol202.uranium.swing.component.SwingAbstractAppComponent
import pl.karol202.uranium.swing.layout.layout
import pl.karol202.uranium.swing.component.SwingContainerComponent
import pl.karol202.uranium.swing.util.*
import java.awt.Container
import java.awt.GridLayout
import java.awt.LayoutManager
import kotlin.math.max
class SwingGridLayout(props: Props) : SwingAbstractAppComponent<SwingGridLayout.Props>(props)
{
data class Props(override val key: Any = AutoKey,
override val swingProps: SwingContainerComponent.Props = SwingContainerComponent.Props(),
val content: List<SwingElement<*>> = emptyList(),
val rows: Prop<Int> = Prop.NoValue,
val columns: Prop<Int> = Prop.NoValue,
val horizontalGap: Prop<Int> = Prop.NoValue,
val verticalGap: Prop<Int> = Prop.NoValue) : UProps,
SwingContainerComponent.PropsProvider<Props>,
PropsProvider<Props>
{
override val gridLayoutProps = this
override fun withSwingProps(builder: Builder<SwingContainerComponent.Props>) = copy(swingProps = swingProps.builder())
override fun withGridLayoutProps(builder: Builder<Props>) = builder()
}
interface PropsProvider<S : PropsProvider<S>> : UProps
{
val gridLayoutProps: Props
fun withGridLayoutProps(builder: Builder<Props>): S
}
override fun URenderScope<Swing>.render() = layout(swingProps = props.swingProps,
content = props.content,
layoutUpdater = ::updateLayout)
private fun updateLayout(container: Container, layout: LayoutManager?) = (layout as? GridLayout ?: GridLayout()).apply {
props.rows.ifPresent { rows = max(it, 1) } // Workaround for prohibition of being both rows and cols equal to 0
props.columns.ifPresent { columns = it }
props.horizontalGap.ifPresent { hgap = it }
props.verticalGap.ifPresent { vgap = it }
}
}
fun SwingRenderScope.gridLayout(key: Any = AutoKey) = gridLayout(props = SwingGridLayout.Props(key))
internal fun SwingRenderScope.gridLayout(props: SwingGridLayout.Props) = component(::SwingGridLayout, props)
private typealias SGLProvider<P> = SwingGridLayout.PropsProvider<P>
fun <P : SGLProvider<P>> SwingElement<P>.withGridLayoutProps(builder: Builder<SwingGridLayout.Props>) =
withProps { withGridLayoutProps(builder) }
fun <P : SGLProvider<P>> SwingElement<P>.contentRows(block: SwingGridRowsBuilder.() -> Unit) =
content(SwingGridRowsBuilder().apply(block))
fun <P : SGLProvider<P>> SwingElement<P>.contentColumns(block: SwingGridColumnsBuilder.() -> Unit) =
content(SwingGridColumnsBuilder().apply(block))
private fun <P : SGLProvider<P>> SwingElement<P>.content(builder: SwingGridBuilder) = withGridLayoutProps {
copy(content = builder.elements, rows = builder.rowsAmount.prop(), columns = builder.columnsAmount.prop())
}
fun <P : SGLProvider<P>> SwingElement<P>.horizontalGap(gap: Int) = withGridLayoutProps { copy(horizontalGap = gap.prop()) }
fun <P : SGLProvider<P>> SwingElement<P>.verticalGap(gap: Int) = withGridLayoutProps { copy(verticalGap = gap.prop()) }
| 0 |
Kotlin
|
0
| 0 |
d15bbc869a1dac11285d9329a49caee32345f63b
| 3,600 |
uranium-swing
|
MIT License
|
LanguageTandem/app/src/main/java/com/yilmazvolkan/languagetandem/repository/TandemRepository.kt
|
yilmazvolkan
| 322,081,184 | false | null |
package com.yilmazvolkan.languagetandem.repository
import com.yilmazvolkan.languagetandem.api.TandemRemoteDataSource
import javax.inject.Inject
class TandemRepository @Inject constructor(
private val remoteDataSource: TandemRemoteDataSource
) {
fun getTandems(page: Int) = remoteDataSource.getTandems(page)
}
| 0 |
Kotlin
|
1
| 1 |
6686ff03337f50b7b0051e9a0dab9f6a6a6f8d0b
| 318 |
find-language-tandem-app
|
MIT License
|
src/jsMain/kotlin/presentation/client/Client.kt
|
Tanexc
| 667,134,735 | false | null |
package presentation.client
import core.di.clientModule
import org.jetbrains.skiko.wasm.onWasmReady
import org.koin.core.context.startKoin
import presentation.features.application.ClientMainApp
import presentation.features.application.components.BrowserViewportWindow
import presentation.style.strings.Strings
import presentation.style.strings.Strings.EN.app_name
import presentation.style.ui.theme.ClientTheme
fun main() {
startKoin {
modules(clientModule)
}
onWasmReady {
BrowserViewportWindow(Strings.EN(app_name)) {
ClientTheme(true) {
ClientMainApp()
}
}
}
}
| 0 |
Kotlin
|
0
| 2 |
d8219c60de5c350c7b6b1d5031166deb0063e557
| 649 |
ComposeWebCakes
|
Apache License 2.0
|
src/test/kotlin/day08_seven_segment/SevenSegmentKtTest.kt
|
barneyb
| 425,532,798 | false |
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
|
package day08_seven_segment
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
private val SINGLE_EXAMPLE =
"acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
private val WORKED_EXAMPLE = """
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
""".trimIndent()
internal class SevenSegmentKtTest {
@Test
fun partOne() {
assertEquals(0, partOne(SINGLE_EXAMPLE))
assertEquals(26, partOne(WORKED_EXAMPLE))
}
@Test
fun partTwo() {
assertEquals(5353, partTwo(SINGLE_EXAMPLE))
assertEquals(61229, partTwo(WORKED_EXAMPLE))
}
}
| 0 |
Kotlin
|
0
| 0 |
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
| 1,436 |
aoc-2021
|
MIT License
|
app/src/main/java/com/github/jing332/tts_server_android/data/dao/SpeechRuleDao.kt
|
jing332
| 536,800,727 | false | null |
package com.github.jing332.tts_server_android.data.dao
import androidx.room.*
import com.github.jing332.tts_server_android.data.entities.SpeechRule
import kotlinx.coroutines.flow.Flow
@Dao
interface SpeechRuleDao {
@get:Query("SELECT * FROM speech_rules ORDER BY `order` ASC")
val all: List<SpeechRule>
@get:Query("SELECT * FROM speech_rules WHERE isEnabled = '1'")
val allEnabled: List<SpeechRule>
@Query("SELECT * FROM speech_rules ORDER BY `order` ASC")
fun flowAll(): Flow<List<SpeechRule>>
@get:Query("SELECT count(*) FROM speech_rules")
val count: Int
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(vararg data: SpeechRule)
@Delete
fun delete(vararg data: SpeechRule)
@Update
fun update(vararg data: SpeechRule)
@Query("SELECT * FROM speech_rules WHERE ruleId = :ruleId AND isEnabled = :isEnabled LIMIT 1")
fun getByRuleId(ruleId: String, isEnabled: Boolean = true): SpeechRule?
// @Query("SELECT * FROM speech_rules WHERE ruleId = :ruleId")
// fun getByRuleId(ruleId: String): SpeechRule?
fun insertOrUpdate(vararg args: SpeechRule) {
for (v in args) {
val old = getByRuleId(v.ruleId)
if (old == null) {
insert(v)
continue
}
if (v.ruleId == old.ruleId && v.version > old.version)
update(v.copy(id = old.id))
}
}
}
| 6 |
Kotlin
|
127
| 1,393 |
8e07e8842cf4cec70154041fcd6a64ad2352d8c8
| 1,435 |
tts-server-android
|
MIT License
|
src/test/kotlin/com/github/kerubistan/kerub/services/impl/HostServiceIT.kt
|
kerubistan
| 19,528,622 | false | null |
package com.github.kerubistan.kerub.services.impl
import com.github.kerubistan.kerub.RestException
import com.github.kerubistan.kerub.createClient
import com.github.kerubistan.kerub.expect
import com.github.kerubistan.kerub.login
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.services.HostAndPassword
import com.github.kerubistan.kerub.services.HostJoinDetails
import com.github.kerubistan.kerub.services.HostService
import com.github.kerubistan.kerub.services.LoginService
import com.github.kerubistan.kerub.testHost
import org.apache.cxf.jaxrs.client.JAXRSClientFactory
import org.hamcrest.CoreMatchers
import org.junit.Assert
import org.junit.Test
import java.util.UUID
import kotlin.test.assertEquals
class HostServiceIT {
@Test
fun security() {
//unauthenticated
checkNoAccess(JAXRSClientFactory.fromClient(createClient(),
HostService::class.java, true), { assertEquals("AUTH1", it.code) })
//end user has nothing to do with hosts
val endUserClient = createClient()
endUserClient.login("enduser","password")
checkNoAccess(JAXRSClientFactory.fromClient(endUserClient,
HostService::class.java, true), { assertEquals("SEC1", it.code) })
}
private fun checkNoAccess(service: HostService, check: (RestException) -> Unit) {
expect(
clazz = RestException::class,
action = { service.search(Host::address.name, "any", 0, Int.MAX_VALUE) },
check = check
)
expect(
clazz = RestException::class,
action = { service.getByAddress("example.com") },
check = check
)
expect(
clazz = RestException::class,
action = { service.joinWithoutPassword(HostJoinDetails(host = testHost) ) },
check = check
)
expect(
clazz = RestException::class,
action = {
service.join(
HostAndPassword(host = testHost, password = "<PASSWORD>")
)
},
check = check
)
expect(
clazz = RestException::class,
action = { service.getById(UUID.randomUUID()) },
check = check
)
expect(
clazz = RestException::class,
action = { service.delete(testHost.id) },
check = check
)
expect(
clazz = RestException::class,
action = { service.listAll(start = 0, limit = 100, sort = Host::address.name) },
check = check
)
}
//TODO: issue #127 make a cucumber story out of this
@Test
fun getPubkey() {
val client = createClient()
val login = JAXRSClientFactory.fromClient(client, LoginService::class.java, true)
login.login(LoginService.UsernamePassword(username = "admin", password = "<PASSWORD>"))
val service = JAXRSClientFactory.fromClient(client,
HostService::class.java, true)
Assert.assertThat(service.getPubkey(), CoreMatchers.notNullValue())
}
}
| 109 |
Kotlin
|
4
| 14 |
99cb43c962da46df7a0beb75f2e0c839c6c50bda
| 2,718 |
kerub
|
Apache License 2.0
|
mobile-sdk/src/main/java/com/github/itwin/mobilesdk/ITMActionable.kt
|
iTwin
| 457,107,127 | false | null |
package com.github.itwin.mobilesdk
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import com.eclipsesource.json.JsonValue
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
/**
* Abstract superclass for [ITMAlert] and [ITMActionSheet].
*
* @param nativeUI The [ITMNativeUI] in which the UI will display.
*/
abstract class ITMActionable(nativeUI: ITMNativeUI): ITMNativeUIComponent(nativeUI) {
protected var continuation: Continuation<JsonValue>? = null
companion object {
/**
* Returns a list of [Action]'s and the cancel action (if defined in the input json).
*
* @param actionsValue An array of [JsonObject] containing the actions.
*/
fun readActions(actionsValue: JsonArray): Pair<List<Action>, Action?> {
val actions: MutableList<Action> = mutableListOf()
var cancelAction: Action? = null
actionsValue.forEach { actionValue ->
val action = Action(actionValue.asObject())
if (action.style == Action.Style.Cancel) {
cancelAction = action
} else {
actions += action
}
}
return Pair(actions, cancelAction)
}
}
/**
* Class representing an action that the user can select.
*/
data class Action(val name: String, val title: String, val style: Style = Style.Default) {
enum class Style {
Default,
Cancel,
Destructive;
companion object {
fun fromString(style: String?) = style?.takeIf { it.isNotEmpty() }?.let { Style.valueOf(style.replaceFirstChar { it.uppercase() }) } ?: Default
}
}
/**
* Constructor using a [JsonObject]
* @param json [JsonObject] containing required `name` and `title` values, as well as optionally a `style` value.
*/
constructor(json: JsonObject): this(json["name"].asString(), json["title"].asString(), Style.fromString(json.get("style")?.asString()))
}
/**
* Implemented by concrete sub-classes to stop showing their user interface. Called by [resume].
*/
abstract fun removeUI()
/**
* Should be called by sub-classes when an action is selected or cancelled.
*/
protected fun resume(result: JsonValue) {
removeUI()
continuation?.resume(result)
continuation = null
}
}
| 2 |
Kotlin
|
1
| 6 |
822b691549be1112c78cb1a593b178179923ce22
| 2,510 |
mobile-sdk-android
|
MIT License
|
app/src/main/java/io/fournkoner/netschool/utils/NumberUtils.kt
|
4nk1r
| 593,159,855 | false | null |
package io.fournkoner.netschool.utils
import kotlin.math.roundToInt
val Int.formattedShortString: String
get() {
check(this >= 0)
val str = toString()
return when (this) {
in 0..999 -> str
in 1_000..9_999 -> "${str[0]}${if (str[1] != '0') str[1] else ""}K"
in 10_000..99_999 -> "${str.take(2)}${if (str[2] != '0') str[2] else ""}K"
in 100_000..999_999 -> "0,${(str.take(2).toInt() / 10f).roundToInt().coerceAtMost(9)}M"
in 1_000_000..9_999_000 -> "${str[0]}${if (str[1] != '0') str[1] else ""}M"
in 10_000_000..99_999_000 -> "${str.take(2)}${if (str[2] != '0') str[2] else ""}M"
in 100_000_000..999_999_000 -> "0,${(str.take(2).toInt() / 10f).roundToInt().coerceAtMost(9)}B"
in 1_000_000_000..9_999_000_000 -> "${str[0]}${if (str[1] != '0') str[1] else ""}B"
in 10_000_000_000..99_999_000_000 -> "${str.take(2)}${if (str[2] != '0') str[2] else ""}B"
in 100_000_000_000..999_999_000_000 -> "${str.take(3)}B"
else -> "WTF"
}
}
| 0 | null |
0
| 1 |
c9312f600574b7b3382046aeaafa8d96e93e2963
| 1,098 |
netschool
|
MIT License
|
src/commonTest/kotlin/sequences/DistinctTest.kt
|
tomuvak
| 511,086,330 | false | null |
package com.tomuvak.util.sequences
import com.tomuvak.testing.*
import kotlin.test.Test
import kotlin.test.assertFalse
class DistinctTest {
@Test fun distinctRequiresPositiveArgument() {
for (i in -3..0)
assertFailsWithTypeAndMessageContaining<IllegalArgumentException>("positive", i) {
Sequence<Int>(mootProvider).distinct(i)
}
}
@Test fun distinctIsIndeedDistinct() =
sequenceOf(0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4).testIntermediateOperation({
distinct(10)
}) { assertValues(0, 1, 2, 3, 4) }
@Test fun distinctIsLazy() = sequenceOf(0, 0, 1, 0, 1, 2).testLazyIntermediateOperation({ distinct(10) }) {
assertStartsWith(0, 1, 2)
}
@Test fun distinctStopsAfterMaxConsecutiveAttempts() {
sequenceOf(0, 0, 1, 0, 1, 2, 0, 1, 2, 3).testIntermediateOperation({ distinct(4) }) { assertValues(0, 1, 2, 3)}
sequenceOf(0, 0, 1, 0, 1, 2, 0, 1, 2).testLazyIntermediateOperation({ distinct(3) }) { assertValues(0, 1, 2)}
}
@Test fun distinctIterationCanBeRequeriedForExhaustionAfterExhaustion() {
val iterator = emptySequence<Int>().distinct(10).iterator()
assertFalse(iterator.hasNext())
assertFalse(iterator.hasNext())
}
@Test fun distinctByRequiresPositiveArgument() {
for (i in -3..0)
assertFailsWithTypeAndMessageContaining<IllegalArgumentException>("positive", i) {
Sequence<Int>(mootProvider).distinctBy(i, mootFunction)
}
}
@Test fun distinctByIsIndeedDistinct() =
sequenceOf(0, 1, 2, 0, 3, 4, 1, 2, 5, 6, 0, 3, 4, 7, 8, 1, 2, 5, 6, 9).testIntermediateOperation({
distinctBy(10) { it / 2 }
}) { assertValues(0, 2, 4, 6, 8) }
@Test fun distinctByIsLazy() = sequenceOf(0, 1, 2, 0, 3, 4).testLazyIntermediateOperation({
distinctBy(10) { it / 2 }
}) { assertStartsWith(0, 2, 4) }
@Test fun distinctByStopsAfterMaxConsecutiveAttempts() {
sequenceOf(0, 1, 2, 0, 3, 4, 1, 2, 5, 6).testIntermediateOperation({
distinctBy(4) { it / 2 }
}) { assertValues(0, 2, 4, 6)}
sequenceOf(0, 1, 2, 0, 3, 4, 1, 2, 5).testLazyIntermediateOperation({
distinctBy(3) { it / 2 }
}) { assertValues(0, 2, 4)}
}
@Test fun distinctByIterationCanBeRequeriedForExhaustionAfterExhaustion() {
val iterator = emptySequence<Int>().distinctBy(10) { it / 2 }.iterator()
assertFalse(iterator.hasNext())
assertFalse(iterator.hasNext())
}
}
| 0 |
Kotlin
|
0
| 0 |
e20cfae9535fd9968542b901c698fdae1a24abc1
| 2,580 |
util
|
MIT License
|
rtron-math/src/test/kotlin/io/rtron/math/transform/Affine2DTest.kt
|
tum-gis
| 258,142,903 | false | null |
/*
* Copyright 2019-2024 Chair of Geoinformatics, Technical University of Munich
*
* 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 io.rtron.math.transform
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.rtron.math.geometry.euclidean.twod.Pose2D
import io.rtron.math.geometry.euclidean.twod.Rotation2D
import io.rtron.math.geometry.euclidean.twod.point.Vector2D
import io.rtron.math.linear.RealMatrix
import io.rtron.math.linear.RealVector
import io.rtron.math.std.HALF_PI
import io.rtron.math.std.QUARTER_PI
class Affine2DTest : FunSpec({
context("TestTransform") {
test("test rotation") {
val point = Vector2D.X_AXIS
val rotationAngle = Rotation2D(HALF_PI)
val affine = Affine2D.of(rotationAngle)
val actualTransformed = affine.transform(point)
actualTransformed shouldBe Vector2D(0.0, 1.0)
}
}
context("TestInverseTransform") {
test("inverse translation transform") {
val point = Vector2D(10.0, 12.0)
val translation = Vector2D(5.0, 2.0)
val affine = Affine2D.of(translation)
val actualTransformed = affine.inverseTransform(point)
actualTransformed shouldBe Vector2D(5.0, 10.0)
}
}
context("TestAffineMultiplication") {
test("test appending") {
val translation = Vector2D(1.0, 2.0)
val affineA = Affine2D.of(translation)
val scaling = RealVector.of(2.0, 3.0)
val affineB = Affine2D.of(scaling)
val expectedValues =
doubleArrayOf(
2.0, 0.0, 1.0,
0.0, 3.0, 2.0,
0.0, 0.0, 1.0,
)
val expectedMatrix = RealMatrix(expectedValues, 3)
val actualAppended = affineA.append(affineB)
val actualMatrix = actualAppended.toMatrix()
actualMatrix.dimension shouldBe expectedMatrix.dimension
expectedMatrix.toDoubleArray() shouldBe actualMatrix.toDoubleArray()
}
}
context("TestPoseTransforms") {
test("test translation") {
val point = Vector2D(5.0, 3.0)
val pose = Pose2D(Vector2D(-10.0, -5.0), Rotation2D(0.0))
val affineTranslation = Affine2D.of(pose.point)
val affineRotation = Affine2D.of(pose.rotation)
val affine = Affine2D.of(affineTranslation, affineRotation)
val actualTransformed = affine.transform(point)
actualTransformed shouldBe Vector2D(-5.0, -2.0)
}
test("inverse transform with pose in origin") {
val point = Vector2D(5.0, 3.0)
val pose = Pose2D(Vector2D(0.0, 0.0), Rotation2D(0.0))
val affine = Affine2D.of(Affine2D.of(pose.point), Affine2D.of(pose.rotation))
val actualTransformed = affine.inverseTransform(point)
actualTransformed shouldBe Vector2D(5.0, 3.0)
}
test("transform with rotated pose in origin") {
val point = Vector2D(5.0, 0.0)
val pose = Pose2D(Vector2D(0.0, 0.0), Rotation2D(HALF_PI))
val affine = Affine2D.of(Affine2D.of(pose.point), Affine2D.of(pose.rotation))
val actualTransformed = affine.transform(point)
actualTransformed shouldBe Vector2D(0.0, 5.0)
}
test("transform with rotated pose and offset point") {
val point = Vector2D(2.0, 3.0)
val pose = Pose2D(Vector2D(0.0, 0.0), Rotation2D(HALF_PI))
val affine = Affine2D.of(Affine2D.of(pose.point), Affine2D.of(pose.rotation))
val actualTransformed = affine.transform(point)
actualTransformed shouldBe Vector2D(-3.0, 2.0)
}
}
context("TestDecomposition") {
test("extract translation point from basic affine") {
val translation = Vector2D(1.0, 2.0)
val affine = Affine2D.of(translation)
val actual = affine.extractTranslation()
actual shouldBe translation
}
test("extract rotation from basic affine") {
val rotation = Rotation2D(QUARTER_PI)
val affine = Affine2D.of(rotation)
val actual = affine.extractRotation()
actual shouldBe rotation
}
test("extract scale vector from basic affine") {
val scaling = RealVector(doubleArrayOf(3.0, 2.0))
val affine = Affine2D.of(scaling)
val actual = affine.extractScaling()
actual shouldBe scaling
}
test("extract rotation from affine with scaling, translation and rotation") {
val scaling = RealVector(doubleArrayOf(3.0, 2.0))
val translation = Vector2D(3.0, 2.0)
val rotation = Rotation2D(HALF_PI)
val affine = Affine2D.of(Affine2D.of(scaling), Affine2D.of(translation), Affine2D.of(rotation))
val actual = affine.extractRotation()
actual.toAngleRadians() shouldBe rotation.toAngleRadians()
}
}
})
| 7 | null |
12
| 46 |
6add55fcd0836a2bd14622d3fd55e6f9e8902056
| 5,634 |
rtron
|
Apache License 2.0
|
src/main/kotlin/model/validation.kt
|
a-polyudov
| 521,347,564 | false |
{"Kotlin": 13327, "CSS": 915, "HTML": 136}
|
package model
inline fun validate(value: Boolean, lazyMessage: () -> String) {
if (!value) {
throw ValidationException(lazyMessage.invoke())
}
}
class ValidationException(message: String) : RuntimeException(message)
| 6 |
Kotlin
|
0
| 5 |
c75c4ff413968d3e6cd0bc1691e50fe569da9da7
| 227 |
klin
|
MIT License
|
core/src/main/java/com/amplifyframework/notifications/pushnotifications/PushNotificationsException.kt
|
aws-amplify
| 177,009,933 | false |
{"Java": 5271326, "Kotlin": 3564857, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874}
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.notifications.pushnotifications
import com.amplifyframework.notifications.NotificationsException
/**
* Exception thrown by Push Notifications category plugins.
* Creates a new exception with a message, root cause, and recovery suggestion.
* @param message An error message describing why this exception was thrown
* @param cause The underlying cause of this exception
* @param recoverySuggestion Text suggesting a way to recover from the error being described
*/
open class PushNotificationsException(
message: String,
recoverySuggestion: String,
cause: Throwable? = null
) : NotificationsException(message, recoverySuggestion, cause)
| 105 |
Java
|
115
| 245 |
14c71f38f052a964b96d7abaff6e157bd21a64d8
| 1,265 |
amplify-android
|
Apache License 2.0
|
odl-core/src/main/kotlin/sk/jt/jnetbios/odl/core/config/DataStoreConfig.kt
|
jaro0149
| 410,344,130 | false |
{"Kotlin": 22914, "Java": 2715}
|
package sk.jt.jnetbios.odl.core.config
import javax.validation.constraints.Positive
import javax.validation.constraints.PositiveOrZero
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.validation.annotation.Validated
/**
* Settings related to the data-store executor.
*
* @property maxDataChangeExecutorPoolSize the maximum thread pool size for the data change notification executor
* @property maxDataChangeExecutorQueueSize the maximum queue size for the data change notification executor
* @property maxDataChangeListenerQueueSize the maximum queue size for the data change listeners
* @property maxDataStoreExecutorQueueSize the maximum queue size for the data store executor
*/
@Validated
@ConfigurationProperties(prefix = "data-store")
internal data class DataStoreConfig(
@field:Positive var maxDataChangeExecutorPoolSize: Int = 4,
@field:PositiveOrZero var maxDataChangeExecutorQueueSize: Int = 2,
@field:PositiveOrZero var maxDataChangeListenerQueueSize: Int = 8,
@field:PositiveOrZero var maxDataStoreExecutorQueueSize: Int = 10
)
| 0 |
Kotlin
|
0
| 0 |
d0b4c16506dd1d972da8522fe529de46114c01f4
| 1,117 |
jnetbios
|
MIT License
|
backend/src/project/layout/ButtonColor.kt
|
MaxMello
| 211,313,972 | false |
{"JavaScript": 710246, "Kotlin": 539611, "Python": 19119, "Dockerfile": 1460, "HTML": 793, "Shell": 554, "CSS": 39}
|
package project.layout
enum class ButtonColor {
DEFAULT,
PRIMARY,
SECONDARY,
RED_TONE,
LOW_SATURATION_RED_TONE,
ORANGE_TONE,
YELLOW_TONE,
YELLOW_GREEN_TONE,
LOW_SATURATION_GREEN_TONE,
GREEN_TONE
}
| 2 |
JavaScript
|
0
| 6 |
831e1be853a63b7059ad8aa942049eeb6f07a74e
| 237 |
ActiveAnno
|
MIT License
|
app/src/main/java/hm/orz/chaos114/android/slideviewer/SlideViewerApplication.kt
|
noboru-i
| 24,023,921 | false | null |
package hm.orz.chaos114.android.slideviewer
import android.app.Activity
import com.google.android.play.core.splitcompat.SplitCompatApplication
import com.squareup.leakcanary.LeakCanary
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasActivityInjector
import hm.orz.chaos114.android.slideviewer.di.DaggerAppComponent
import hm.orz.chaos114.android.slideviewer.ui.CrashReportingTree
import hm.orz.chaos114.android.slideviewer.util.AnalyticsManager
import timber.log.Timber
import javax.inject.Inject
class SlideViewerApplication : SplitCompatApplication(), HasActivityInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
@Inject
lateinit var analyticsManager: AnalyticsManager
override fun onCreate() {
super.onCreate()
DaggerAppComponent.builder()
.application(this)
.build()
.inject(this)
LeakCanary.install(this)
Timber.plant(if (BuildConfig.DEBUG) Timber.DebugTree() else CrashReportingTree())
analyticsManager.updateUserProperty()
}
override fun activityInjector(): AndroidInjector<Activity>? {
return dispatchingAndroidInjector
}
}
| 9 |
Kotlin
|
0
| 0 |
c6b80b3f51307d7714efafd25b9da86baf129e09
| 1,279 |
SlideViewer
|
MIT License
|
app/src/main/java/com/wang/sunnyweather/logic/model/Place.kt
|
qingzhou1994
| 473,091,753 | false | null |
package com.wang.sunnyweather.logic.model
import com.google.gson.annotations.SerializedName
data class Place(
val name: String, val location: Location,
@SerializedName("formatted_address") val address: String
)
| 0 |
Kotlin
|
0
| 0 |
9f5104169e63be5c4d5a599b1e08bbb7bd242222
| 221 |
SunnyWeather
|
Apache License 2.0
|
koin-projects/examples/android-mvvm-coroutines/src/main/kotlin/fr/ekito/myweatherapp/di/local_datasource_module.kt
|
EslamHussein
| 163,691,953 | true |
{"Kotlin": 518751, "CSS": 32204, "Java": 3568, "Shell": 473}
|
package fr.ekito.myweatherapp.di
import fr.ekito.myweatherapp.data.WeatherDatasource
import fr.ekito.myweatherapp.data.local.AndroidJsonReader
import fr.ekito.myweatherapp.data.local.JsonReader
import fr.ekito.myweatherapp.data.local.LocalFileDataSource
import org.koin.dsl.module.module
import org.koin.experimental.builder.singleBy
/**
* Local Json Files Datasource
*/
val localAndroidDatasourceModule = module {
singleBy<JsonReader, AndroidJsonReader>()
single<WeatherDatasource> { LocalFileDataSource(get(), true) }
}
| 0 |
Kotlin
|
0
| 0 |
bdfcec953b256e98326c997c90a4ead482fdbecd
| 533 |
koin
|
Apache License 2.0
|
transferwise/src/main/java/com/transferwise/banks/transfer/extradetails/ExtraDetailsWebService.kt
|
Ryggs
| 237,440,757 | true |
{"Kotlin": 446684}
|
/*
* Copyright 2019 TransferWise Ltd.
*
* 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.transferwise.banks.transfer.extradetails
import com.transferwise.banks.api.BanksWebService
import com.transferwise.banks.api.request.TransferRequest
import com.transferwise.dynamicform.api.DynamicFormsWebService
internal class ExtraDetailsWebService(
private val webService: BanksWebService,
private val customerId: Int,
private val quoteId: String,
private val recipientId: Int
) : DynamicFormsWebService {
override suspend fun getForm() =
webService.getTransferRequirements(customerId, TransferRequest(quoteId, recipientId, emptyMap()))
override suspend fun refreshForm(attributes: Map<String, String?>, details: Map<String, Any?>) =
webService.getTransferRequirements(customerId, TransferRequest(quoteId, recipientId, details))
}
| 0 | null |
0
| 1 |
54688a6bd7054c2ed7d5db325591bf26a97286bd
| 1,391 |
banks-reference-android
|
Apache License 2.0
|
app/src/main/java/be/digitalia/fosdem/viewmodels/BookmarksViewModel.kt
|
jsoriano
| 332,221,844 | true |
{"Kotlin": 297541}
|
package be.digitalia.fosdem.viewmodels
import android.app.Application
import android.text.format.DateUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.switchMap
import be.digitalia.fosdem.db.AppDatabase
import be.digitalia.fosdem.livedata.LiveDataFactory
import be.digitalia.fosdem.model.Event
import java.util.concurrent.TimeUnit
class BookmarksViewModel(application: Application) : AndroidViewModel(application) {
private val appDatabase = AppDatabase.getInstance(application)
private val upcomingOnlyLiveData = MutableLiveData<Boolean>()
val bookmarks: LiveData<List<Event>> = upcomingOnlyLiveData.switchMap { upcomingOnly: Boolean ->
if (upcomingOnly) {
// Refresh upcoming bookmarks every 2 minutes
LiveDataFactory.interval(2L, TimeUnit.MINUTES)
.switchMap {
appDatabase.bookmarksDao.getBookmarks(System.currentTimeMillis() - TIME_OFFSET)
}
} else {
appDatabase.bookmarksDao.getBookmarks(-1L)
}
}
var upcomingOnly: Boolean
get() = upcomingOnlyLiveData.value == true
set(value) {
if (value != upcomingOnlyLiveData.value) {
upcomingOnlyLiveData.value = value
}
}
fun removeBookmarks(eventIds: LongArray) {
appDatabase.bookmarksDao.removeBookmarksAsync(*eventIds)
}
companion object {
// In upcomingOnly mode, events that just started are still shown for 5 minutes
private const val TIME_OFFSET = 5L * DateUtils.MINUTE_IN_MILLIS
}
}
| 0 | null |
0
| 0 |
4e8959ce843fd00cbfa5c683dd01097f0c2c5078
| 1,691 |
fosdem-companion-android
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/backupgateway/CfnHypervisorDsl.kt
|
F43nd1r
| 643,016,506 | false |
{"Kotlin": 5407210}
|
package com.faendir.awscdkkt.generated.services.backupgateway
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.backupgateway.CfnHypervisor
import software.amazon.awscdk.services.backupgateway.CfnHypervisorProps
import software.constructs.Construct
@Generated
public fun Construct.cfnHypervisor(id: String, initializer: @AwsCdkDsl CfnHypervisor.() -> Unit =
{}): CfnHypervisor = CfnHypervisor(this, id).apply(initializer)
@Generated
public fun Construct.cfnHypervisor(
id: String,
props: CfnHypervisorProps,
initializer: @AwsCdkDsl CfnHypervisor.() -> Unit = {},
): CfnHypervisor = CfnHypervisor(this, id, props).apply(initializer)
@Generated
public fun Construct.buildCfnHypervisor(id: String, initializer: @AwsCdkDsl
CfnHypervisor.Builder.() -> Unit = {}): CfnHypervisor = CfnHypervisor.Builder.create(this,
id).apply(initializer).build()
| 1 |
Kotlin
|
0
| 4 |
e80fe2769852069fdf68382f2ee677cc32dbe73f
| 966 |
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/ru/ra66it/updaterforspotify/data/storage/SharedPreferencesHelper.kt
|
2Ra66it
| 124,287,161 | false | null |
package ru.ra66it.updaterforspotify.data.storage
import android.content.SharedPreferences
import javax.inject.Inject
class SharedPreferencesHelper @Inject constructor(
private val sharedPreferences: SharedPreferences
) {
private val prefNotification = "prefNotification"
private val prefCheckIntervalDay = "prefCheckIntervalDay"
var isEnableNotification: Boolean
get() = sharedPreferences.getBoolean(prefNotification, true)
set(isOn) = sharedPreferences.edit().putBoolean(prefNotification, isOn).apply()
var checkIntervalDay: Long
get() = sharedPreferences.getLong(prefCheckIntervalDay, 1)
set(interval) = sharedPreferences.edit().putLong(prefCheckIntervalDay, interval).apply()
}
| 11 |
Kotlin
|
13
| 74 |
38e591d9def7dae9147514929909d9d1007070c0
| 742 |
updater-for-spotify
|
MIT License
|
shared/src/androidMain/kotlin/com/example/moveeapp_compose_kmm/permission/PermissionsUtil.kt
|
adessoTurkey
| 673,248,729 | false |
{"Kotlin": 334470, "Swift": 3538, "Ruby": 101}
|
package com.example.moveeapp_compose_kmm.permission
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.example.moveeapp_compose_kmm.core.getActivity
internal fun Context.findActivity(): Activity {
return getActivity()
?: throw IllegalStateException("Permissions should be called in the context of an Activity")
}
internal fun Context.checkPermission(permission: String): Boolean {
return ContextCompat.checkSelfPermission(this, permission) ==
PackageManager.PERMISSION_GRANTED
}
internal fun Activity.shouldShowRationale(permission: String): Boolean {
return ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
}
@Composable
internal fun PermissionLifecycleCheckerEffect(
permissionState: MutablePermissionState,
lifecycleEvent: Lifecycle.Event = Lifecycle.Event.ON_RESUME
) {
// Check if the permission was granted when the lifecycle is resumed.
// The user might've gone to the Settings screen and granted the permission.
val permissionCheckerObserver = remember(permissionState) {
LifecycleEventObserver { _, event ->
if (event == lifecycleEvent) {
// If the permission is revoked, check again.
// We don't check if the permission was denied as that triggers a process restart.
if (permissionState.status != PermissionStatus.Granted) {
permissionState.refreshPermissionStatus()
}
}
}
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, permissionCheckerObserver) {
lifecycle.addObserver(permissionCheckerObserver)
onDispose { lifecycle.removeObserver(permissionCheckerObserver) }
}
}
| 6 |
Kotlin
|
3
| 78 |
2dbbd48654ee482258c37f0e51e52eb6af15ec3c
| 2,168 |
compose-multiplatform-sampleapp
|
Apache License 2.0
|
google-auto-service-ksp/src/main/kotlin/com/livk/auto/service/ksp/GoogleAutoServiceProcessorProvider.kt
|
livk-cloud
| 441,105,335 | false |
{"Kotlin": 92224}
|
package com.livk.auto.service.ksp
import com.google.devtools.ksp.closestClassDeclaration
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import java.io.IOException
/**
* <p>
* GoogleAutoServiceProcessorProvider
* </p>
*
* @author livk
* @date 2024/6/20
*/
class GoogleAutoServiceProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor =
GoogleAutoServiceProcessor(environment)
internal class GoogleAutoServiceProcessor(environment: SymbolProcessorEnvironment) :
AbstractProcessor(environment) {
override fun supportAnnotation(): String = "com.google.auto.service.AutoService"
override fun accept(annotation: KSAnnotation, symbolAnnotation: KSClassDeclaration) {
for (any in getArgument(annotation, "value") as List<*>) {
val implService = any as KSType
val providerName = implService.declaration.closestClassDeclaration()?.toBinaryName()
providers.put(providerName, symbolAnnotation.toBinaryName() to symbolAnnotation.containingFile!!)
}
}
override fun generateAndClearConfigFiles() {
if (!providers.isEmpty) {
for (providerInterface in providers.keySet()) {
val resourceFile = "META-INF/services/${providerInterface}"
logger.info(supportAnnotation() + " working on resource file: $resourceFile")
try {
val autoService = providers[providerInterface].map { it.first }
logger.info(supportAnnotation() + " file contents: $autoService")
val dependencies =
Dependencies(true, *providers[providerInterface].map { it.second }.toTypedArray())
generator.createNewFile(dependencies, "", resourceFile, "").bufferedWriter().use { writer ->
for (service in autoService) {
writer.write(service)
writer.newLine()
}
}
logger.info(supportAnnotation() + " wrote to: $resourceFile")
} catch (e: IOException) {
logger.error(supportAnnotation() + " unable to create $resourceFile, $e")
}
}
providers.clear()
}
}
}
}
| 1 |
Kotlin
|
7
| 26 |
c7e3ac94714adc686232aac9d2c2b6a9936e08b6
| 2,858 |
spring-cloud-kotlin
|
Apache License 2.0
|
designer/src/com/android/tools/idea/uibuilder/structure/NlVisibilityGutterPanel.kt
|
JetBrains
| 60,701,247 | false | null |
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.tools.idea.uibuilder.structure
import com.android.tools.adtui.common.AdtUiUtils
import com.android.tools.adtui.common.secondaryPanelBackground
import com.android.tools.idea.common.model.NlComponent
import com.android.tools.idea.res.RESOURCE_ICON_SIZE
import com.google.common.annotations.VisibleForTesting
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.util.Disposer
import com.intellij.ui.CollectionListModel
import java.awt.Component
import java.awt.Dimension
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.event.TreeExpansionEvent
import javax.swing.event.TreeExpansionListener
/**
* Panel that shows the view's visibility in the gutter next to the component tree. Clicking each
* icon would show popup menu that allows users to choose visibility.
*/
open class NlVisibilityGutterPanel : JPanel(), TreeExpansionListener, Disposable {
companion object {
private const val PADDING_X = 10
const val WIDTH = RESOURCE_ICON_SIZE + PADDING_X
}
@VisibleForTesting val list = NlVisibilityJBList()
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
alignmentX = Component.CENTER_ALIGNMENT
background = secondaryPanelBackground
preferredSize = Dimension(WIDTH, 0)
list.model = CollectionListModel()
list.cellRenderer = NlVisibilityButtonCellRenderer()
// These are required to remove blue bazel when focused.
list.border = null
list.isFocusable = false
isFocusable = false
add(list)
Disposer.register(this, list)
}
override fun updateUI() {
super.updateUI()
border = BorderFactory.createMatteBorder(0, 1, 0, 0, AdtUiUtils.DEFAULT_BORDER_COLOR)
}
/** Update the gutter icons according to the tree paths. */
fun update(tree: JTree) {
val application = ApplicationManager.getApplication()
if (!application.isReadAccessAllowed) {
return runReadAction { update(tree) }
}
val toReturn = ArrayList<ButtonPresentation>()
for (i in 0 until tree.rowCount) {
val path = tree.getPathForRow(i)
val last = path.lastPathComponent
if (last is NlComponent) {
toReturn.add(createItem(last))
} else {
// Anything else (e.g. Referent id) we don't support visibility change.
toReturn.add(createItem())
}
}
list.model = CollectionListModel(toReturn)
revalidate()
}
private fun createItem(component: NlComponent? = null): ButtonPresentation {
if (component == null) {
return ButtonPresentation()
}
val model = NlVisibilityModel(component)
return ButtonPresentation(model)
}
override fun treeExpanded(event: TreeExpansionEvent?) {
update(event?.source as JTree)
}
override fun treeCollapsed(event: TreeExpansionEvent?) {
update(event?.source as JTree)
}
override fun dispose() {
removeAll()
}
}
| 5 | null |
230
| 948 |
10110983c7e784122d94c7467e9d243aba943bf4
| 3,669 |
android
|
Apache License 2.0
|
app/src/test/java/com/babylone/playbook/core/mvp/TestSchedulersFactory.kt
|
itslonua
| 182,047,511 | false |
{"Kotlin": 73294}
|
package com.babylone.playbook.core.mvp
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
object TestSchedulersFactory : SchedulerProvider {
override fun io() = Schedulers.trampoline()
override fun mainThread(): Scheduler = Schedulers.trampoline()
}
| 0 |
Kotlin
|
0
| 0 |
ec7d289f5e41056f4776804ae008b642f8bb70ae
| 283 |
babylon-samples-mvi
|
MIT License
|
lib/src/main/java/net/imoya/android/media/audio/raw/RawAudioFormat.kt
|
IceImo-P
| 452,667,694 | false |
{"Kotlin": 82456}
|
/*
* Copyright (C) 2022 IceImo-P
*
* 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 net.imoya.android.media.audio.raw
import android.media.AudioFormat
import android.media.MediaFormat
import net.imoya.android.media.audio.AudioUtility
/**
* [RawAudio] のデータ形式を表します。
*
* @param mediaFormat [MediaFormat]
*/
class RawAudioFormat(private val mediaFormat: MediaFormat) {
private lateinit var audioFormatCache: AudioFormat
/**
* データ形式を表す [AudioFormat]
*/
val audioFormat: AudioFormat
get() {
if (!this::audioFormatCache.isInitialized) {
audioFormatCache = AudioUtility.toAudioFormatFrom(mediaFormat)
}
return audioFormatCache
}
/**
* チャンネル数
*/
val channels: Int
get() = mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
/**
* 1 チャンネル の 1 サンプルを構成するバイト数
*/
val bytesPerSampleAtChannel: Int
get() = when (audioFormat.encoding) {
AudioFormat.ENCODING_PCM_8BIT -> 1
AudioFormat.ENCODING_PCM_16BIT -> 2
AudioFormat.ENCODING_PCM_FLOAT -> 4
else -> throw IllegalArgumentException("Unsupported PCM encoding: ${audioFormat.encoding}")
}
/**
* 全チャンネルの 1 サンプルを構成するバイト数
*/
val bytesPerSample: Int
get() = audioFormat.channelCount * bytesPerSampleAtChannel
/**
* 1 秒当たりのサンプル数(サンプリング周波数, サンプリングレートと同値)
*/
val samplesPerSecond: Int
get() = audioFormat.sampleRate
override fun toString(): String {
return "audio/raw, $mediaFormat"
}
}
| 0 |
Kotlin
|
0
| 0 |
28f734cb93090ed643e51db5c83c1b924bdac39c
| 2,113 |
ImoyaAndroidMediaLib
|
Apache License 2.0
|
app/src/main/java/top/jiecs/screener/ui/displaymode/DisplayModeFragment.kt
|
jiesou
| 727,220,282 | false |
{"Kotlin": 26724}
|
package top.jiecs.screener.ui.displaymode
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.PopupMenu
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.lifecycle.Lifecycle
import top.jiecs.screener.R
/**
* A fragment for configuring the display modes
*/
class DisplayModeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_display_mode, container, false)
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = LinearLayoutManager(context)
adapter = DisplayModeRecyclerViewAdapter(DisplayModeContent.DISPLAY_MODES)
}
}
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, RESUMED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.display_mode_action_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return when (menuItem.itemId) {
R.id.new_display_mode -> {
// dialog to add a new display mode
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
return view
}
}
| 5 |
Kotlin
|
15
| 85 |
cf75ba9fd03701f5dd36186cd6d3882d308f3f2b
| 2,319 |
Android-Screener
|
MIT License
|
shared/src/main/java/namnh/clean/shared/adapter/loadmore/LoadMoreAdapter.kt
|
namnh-0652
| 247,247,289 | true | null |
package namnh.clean.shared.adapter.loadmore
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import namnh.clean.shared.R
class LoadMoreAdapter internal constructor(
adapter: RecyclerView.Adapter<*>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var progressView: View? = null
private var progressResId = View.NO_ID
var reachEndView: View? = null
private var reachEndResId = View.NO_ID
var loadFailedView: View? = null
private var loadFailedResId = View.NO_ID
var retryMessage: String? = null
var reachEndMessage: String? = null
/**
* At least your adapter count must be greater or equal this number for activating the load more callback
*/
var visibleThreshold: Int = DEFAULT_THRESHOLD
lateinit var originalAdapter: RecyclerView.Adapter<*>
private var recyclerView: RecyclerView? = null
private var onLoadMoreListener: OnLoadMoreListener? = null
private lateinit var loadMoreController: LoadMoreController
private var isLoading: Boolean = false
private var shouldRemove: Boolean = false
private var showReachEnd: Boolean = false
private var isLoadFailed: Boolean = false
private var hasReachedEnd: Boolean = false
/**
* Deciding whether to trigger loading
*/
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!loadMoreEnabled || isLoading || onLoadMoreListener == null) {
return
}
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
val layoutManager = recyclerView.layoutManager
val isBottom = when (layoutManager) {
is LinearLayoutManager -> layoutManager.findLastVisibleItemPosition() >= layoutManager.getItemCount() - 1
is StaggeredGridLayoutManager -> {
val into = IntArray(layoutManager.spanCount)
layoutManager.findLastVisibleItemPositions(into)
last(into) >= layoutManager.getItemCount() - 1
}
else -> (layoutManager as GridLayoutManager).findLastVisibleItemPosition() >= layoutManager.getItemCount() - 1
}
if (isBottom && itemCount >= visibleThreshold) {
isLoading = true
onLoadMoreListener!!.onLoadMore()
}
}
}
}
var loadMoreEnabled: Boolean
get() = loadMoreController.loadMoreEnabled && originalAdapter.itemCount >= 0
set(enabled) {
this.loadMoreController.loadMoreEnabled = enabled
}
private val onLoadMoreStateChangedListener = object : LoadMoreController.OnLoadMoreStateChangeListener {
override fun notifyChanged() {
shouldRemove = true
}
override fun notifyLoadFailed(isFailed: Boolean) {
isLoadFailed = isFailed
notifyFooterHolderChanged()
}
override fun notifyReachEnd(reachEnd: Boolean) {
hasReachedEnd = reachEnd
notifyFooterHolderChanged()
}
}
private val dataObserver: RecyclerView.AdapterDataObserver = object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
if (shouldRemove) {
shouldRemove = false
}
[email protected]()
isLoading = false
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
if (shouldRemove && positionStart == originalAdapter.itemCount) {
shouldRemove = false
}
if (positionStart == 0) {
[email protected]()
} else {
[email protected](positionStart, itemCount)
}
isLoading = false
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
if (shouldRemove && positionStart == originalAdapter.itemCount) {
shouldRemove = false
}
if (positionStart == 0) {
[email protected]()
} else {
[email protected](positionStart, itemCount, payload)
}
isLoading = false
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
// when no data is initialized (has loadMoreView)
// should remove loadMoreView before notifyItemRangeInserted
if (getItemCount() == 1) {
[email protected](0)
}
if (positionStart == 0) {
[email protected]()
} else {
[email protected](positionStart, itemCount)
}
notifyFooterHolderChanged()
isLoading = false
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
if (shouldRemove && positionStart == originalAdapter.itemCount) {
shouldRemove = false
}
/*
use notifyItemRangeRemoved after clear item, can throw IndexOutOfBoundsException
@link RecyclerView#tryGetViewHolderForPositionByDeadline
fix java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position
*/
var shouldSync = false
if (loadMoreController.loadMoreEnabled && originalAdapter.itemCount == 0) {
loadMoreEnabled = false
shouldSync = true
// when use onItemRangeInserted(0, count) after clear item
// recyclerView will auto scroll to bottom, because has one item(loadMoreView)
// remove loadMoreView
if (getItemCount() == 1) {
[email protected](0)
}
}
if (positionStart == 0) {
[email protected]()
} else {
[email protected](positionStart, itemCount)
}
if (shouldSync) {
loadMoreEnabled = true
}
isLoading = false
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
if (shouldRemove && (fromPosition == originalAdapter.itemCount || toPosition == originalAdapter.itemCount)) {
throw IllegalArgumentException(
"can not move last position after setLoadMoreEnabled(false)")
}
[email protected](fromPosition, toPosition)
isLoading = false
}
}
init {
registerAdapter(adapter)
}
private fun registerAdapter(adapter: RecyclerView.Adapter<*>?) {
if (adapter == null) {
throw NullPointerException("adapter can not be null!")
}
originalAdapter = adapter
originalAdapter.registerAdapterDataObserver(dataObserver)
loadMoreController = LoadMoreController(onLoadMoreStateChangedListener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
TYPE_PROGRESS -> {
if (progressResId != View.NO_ID) {
progressView = LoadMoreHelper.inflate(parent, progressResId)
}
if (progressView != null) {
return ProgressHolder(progressView!!)
}
return ProgressHolder(LoadMoreHelper.inflate(parent, R.layout.layout_progress))
}
TYPE_REACH_END -> {
if (reachEndResId != View.NO_ID) {
reachEndView = LoadMoreHelper.inflate(parent, reachEndResId)
}
if (reachEndView != null) {
return ReachEndHolder(reachEndView!!)
}
return ReachEndHolder(LoadMoreHelper.inflate(parent, R.layout.layout_info))
}
TYPE_LOAD_FAILED -> {
if (loadFailedResId != View.NO_ID) {
loadFailedView = LoadMoreHelper.inflate(parent, loadFailedResId)
}
var view = loadFailedView
if (view == null) {
view = LoadMoreHelper.inflate(parent, R.layout.layout_retry)
}
return LoadFailedHolder(view, loadMoreController, onLoadMoreListener)
}
else -> return originalAdapter.onCreateViewHolder(parent, viewType)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int,
payloads: List<Any>) {
when (holder) {
is ProgressHolder -> {
// TODO Checking later
// Fix LoadMore in Playlist Detail when dragging to reorder videos of playlist
// Removed !canScroll(recyclerView?.layoutManager?.layoutDirection ?: RecyclerView.VERTICAL)
if (onLoadMoreListener != null && !isLoading && itemCount >= visibleThreshold) {
isLoading = true
// fix Cannot call this method while RecyclerView is computing a layout or scrolling
recyclerView?.post { onLoadMoreListener!!.onLoadMore() }
}
holder.bind(originalAdapter.itemCount >= visibleThreshold)
}
is ReachEndHolder -> {
holder.bind(reachEndMessage)
}
is LoadFailedHolder -> {
holder.bind(retryMessage)
}
else -> {
@Suppress("UNCHECKED_CAST")
(originalAdapter as RecyclerView.Adapter<RecyclerView.ViewHolder>).onBindViewHolder(
holder, position, payloads)
}
}
}
override fun getItemCount(): Int {
val count = originalAdapter.itemCount
if (count == 0) return 0
return when {
loadMoreEnabled -> count + 1
showReachEnd -> count + 1
else -> count + if (shouldRemove) 1 else 0
}
}
override fun getItemViewType(position: Int): Int {
val isLastItem = position == originalAdapter.itemCount
if (isLastItem && isLoadFailed) {
return TYPE_LOAD_FAILED
}
if (isLastItem && (loadMoreEnabled || shouldRemove)) {
return TYPE_PROGRESS
} else if (isLastItem && showReachEnd && !loadMoreEnabled) {
return TYPE_REACH_END
}
return originalAdapter.getItemViewType(position)
}
private fun canScroll(layoutDirection: Int): Boolean {
if (recyclerView == null) {
throw NullPointerException(
"recyclerView is null, you should setAdapter(recyclerAdapter);")
}
return recyclerView?.canScrollVertically(layoutDirection) ?: false
}
fun setProgressView(@LayoutRes resId: Int) {
progressResId = resId
}
fun setReachEndView(@LayoutRes resId: Int) {
reachEndResId = resId
}
fun setLoadFailedView(@LayoutRes resId: Int) {
loadFailedResId = resId
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
this.recyclerView = recyclerView
recyclerView.addOnScrollListener(onScrollListener)
val layoutManager = recyclerView.layoutManager
if (layoutManager is GridLayoutManager) {
val originalSizeLookup = layoutManager.spanSizeLookup
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val itemViewType = getItemViewType(position)
if (itemViewType == TYPE_PROGRESS
|| itemViewType == TYPE_REACH_END
|| itemViewType == TYPE_LOAD_FAILED) {
return layoutManager.spanCount
} else if (originalSizeLookup != null) {
return originalSizeLookup.getSpanSize(position)
}
return 1
}
}
}
}
private fun last(lastPositions: IntArray): Int {
var last = lastPositions[0]
for (value in lastPositions) {
if (value > last) {
last = value
}
}
return last
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
recyclerView.removeOnScrollListener(onScrollListener)
originalAdapter.unregisterAdapterDataObserver(dataObserver)
this.recyclerView = null
}
fun setLoadMoreListener(listener: OnLoadMoreListener) {
onLoadMoreListener = listener
onLoadMoreListener?.onPrepared(loadMoreController)
}
fun setShowReachEnd(enabled: Boolean) {
showReachEnd = enabled
}
private fun notifyFooterHolderChanged() {
if (loadMoreEnabled) {
[email protected](originalAdapter.itemCount)
} else if (shouldRemove) {
shouldRemove = false
/*
fix IndexOutOfBoundsException when setLoadMoreEnabled(false) and then use onItemRangeInserted
@see android.support.v7.widget.RecyclerView.Recycler#validateViewHolderForOffsetPosition(RecyclerView.ViewHolder)
*/
val position = originalAdapter.itemCount
val viewHolder = recyclerView?.findViewHolderForAdapterPosition(position)
if (viewHolder is ProgressHolder) {
[email protected](position)
} else {
[email protected](position)
}
}
}
class ProgressHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
LoadMoreHelper.setItemViewFullSpan(itemView)
}
fun bind(isVisible: Boolean) {
if (isVisible == itemView.isVisible) return
itemView.visibility = if (isVisible) View.VISIBLE else View.INVISIBLE
}
}
class ReachEndHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textInfo = itemView.findViewById<TextView>(R.id.info_message)
init {
LoadMoreHelper.setItemViewFullSpan(itemView)
}
fun bind(reachEndMsg: String?) {
if (textInfo != null && !reachEndMsg.isNullOrEmpty()) {
textInfo.text = reachEndMsg
}
}
}
class LoadFailedHolder internal constructor(itemView: View,
private val loadMoreController: LoadMoreController,
val listener: OnLoadMoreListener?) : RecyclerView.ViewHolder(itemView) {
private val btnRetry = itemView.findViewById<View>(R.id.retry_button)
private val textRetry = itemView.findViewById<TextView>(R.id.retry_message)
init {
LoadMoreHelper.setItemViewFullSpan(itemView)
if (btnRetry != null) {
btnRetry.setOnClickListener {
reload()
}
} else {
itemView.setOnClickListener {
reload()
}
}
}
fun bind(retryMsg: String?) {
if (textRetry != null && !retryMsg.isNullOrEmpty()) {
textRetry.text = retryMsg
}
}
private fun reload() {
loadMoreController.setLoadFailed(false)
listener?.onLoadMore()
}
}
interface OnLoadMoreListener {
fun onPrepared(loadMoreController: LoadMoreController?)
fun onLoadMore()
}
companion object {
// DON'T make your Recycler's ViewType like below
const val TYPE_PROGRESS = 99997
const val TYPE_REACH_END = 99998
const val TYPE_LOAD_FAILED = 99999
const val DEFAULT_THRESHOLD = 10
}
}
| 0 | null |
0
| 0 |
d69bdc56e0e032dcb242a1f92e85a1c513ccf799
| 16,866 |
CleanAndroid
|
Apache License 2.0
|
svalidate-core/src/test/java/com/samwoodall/svalidate/ValidatorTest.kt
|
samwoodall
| 150,664,653 | false | null |
package com.samwoodall.svalidate
import android.content.Context
import android.text.Editable
import android.widget.EditText
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.junit.MockitoJUnit
class ValidatorTest {
@Rule
@JvmField
val rule = MockitoJUnit.rule()
private val editText = mock<EditText>()
private val context = mock<Context>()
private val editable = mock<Editable>()
@Before
fun setup() {
whenever(editText.context).thenReturn(context)
whenever(context.getString(any())).thenReturn("")
whenever(editText.error).thenReturn("")
whenever(editText.text).thenReturn(editable)
}
@Test
fun `success case with checkLessThan`() {
val twoLetterExample = "ab"
val validator = Validator().checkLessThan(3)
whenever(editable.toString()).thenReturn(twoLetterExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkLessThan`() {
val threeLetterExample = "aba"
val validator = Validator().checkLessThan(3)
whenever(editable.toString()).thenReturn(threeLetterExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkNotBlank`() {
val notBlankExample = "ab"
val validator = Validator().checkNotBlank()
whenever(editable.toString()).thenReturn(notBlankExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkNotBlank`() {
val blankExample = ""
val validator = Validator().checkNotBlank()
whenever(editable.toString()).thenReturn(blankExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkGreaterThan`() {
val threeLetterExample = "aba"
val validator = Validator().checkGreaterThan(2)
whenever(editable.toString()).thenReturn(threeLetterExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkGreaterThan`() {
val twoLetterExample = "ab"
val validator = Validator().checkGreaterThan(2)
whenever(editable.toString()).thenReturn(twoLetterExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAllLower`() {
val allLowerExample = "aa"
val validator = Validator().checkAllLower()
whenever(editable.toString()).thenReturn(allLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAllLower`() {
val startsWithUpperThenLowerExample = "Aa"
val validator = Validator().checkAllLower()
whenever(editable.toString()).thenReturn(startsWithUpperThenLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAllUpper`() {
val allUpperExample = "AA"
val validator = Validator().checkAllUpper()
whenever(editable.toString()).thenReturn(allUpperExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAllUpper`() {
val startsWithUpperThenLowerExample = "Aa"
val validator = Validator().checkAllUpper()
whenever(editable.toString()).thenReturn(startsWithUpperThenLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAtLeastOneLower`() {
val startsWithUpperThenLowerExample = "Aa"
val validator = Validator().checkAtLeastOneLower()
whenever(editable.toString()).thenReturn(startsWithUpperThenLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAtLeastOneLower`() {
val allUpperExample = "AA"
val validator = Validator().checkAtLeastOneLower()
whenever(editable.toString()).thenReturn(allUpperExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAtLeastOneUpper`() {
val allUpperExample = "AA"
val validator = Validator().checkAtLeastOneUpper()
whenever(editable.toString()).thenReturn(allUpperExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAtLeastOneUpper`() {
val allLowerExample = "aa"
val validator = Validator().checkAtLeastOneUpper()
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAtLeastOneDigit`() {
val oneDigitExample = "sdsd6"
val validator = Validator().checkAtLeastOneDigit()
whenever(editable.toString()).thenReturn(oneDigitExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAtLeastOneDigit`() {
val allLowerExample = "aa"
val validator = Validator().checkAtLeastOneDigit()
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAtLeastOneLetter`() {
val oneLetterExample = "s234"
val validator = Validator().checkAtLeastOneLetter()
whenever(editable.toString()).thenReturn(oneLetterExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAtLeastOneLetter`() {
val allDigitsExample = "33"
val validator = Validator().checkAtLeastOneLetter()
whenever(editable.toString()).thenReturn(allDigitsExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkStartsWithUpper`() {
val startsWithUpperThenLowerExample = "Aa"
val validator = Validator().checkStartsWithUpper()
whenever(editable.toString()).thenReturn(startsWithUpperThenLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkStartsWithUpper`() {
val allLowerExample = "aa"
val validator = Validator().checkStartsWithUpper()
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAllLetters`() {
val startsWithUpperThenLowerExample = "Aa"
val validator = Validator().checkAllLetters()
whenever(editable.toString()).thenReturn(startsWithUpperThenLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAllLetters`() {
val oneLetterExample = "s234"
val validator = Validator().checkAllLetters()
whenever(editable.toString()).thenReturn(oneLetterExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAllNumbers`() {
val allDigitsExample = "33"
val validator = Validator().checkAllNumbers()
whenever(editable.toString()).thenReturn(allDigitsExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAllNumbers`() {
val oneLetterExample = "s234"
val validator = Validator().checkAllNumbers()
whenever(editable.toString()).thenReturn(oneLetterExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkAllAlphanumeric`() {
val oneLetterExample = "s234"
val validator = Validator().checkAllAlphanumeric()
whenever(editable.toString()).thenReturn(oneLetterExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkAllAlphanumeric`() {
val oneSpecialCharExample = "s234_"
val validator = Validator().checkAllAlphanumeric()
whenever(editable.toString()).thenReturn(oneSpecialCharExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkNoLetters`() {
val allDigitsExample = "33"
val validator = Validator().checkNoLetters()
whenever(editable.toString()).thenReturn(allDigitsExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkNoLetters`() {
val oneSpecialCharExample = "s234_"
val validator = Validator().checkNoLetters()
whenever(editable.toString()).thenReturn(oneSpecialCharExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkNoNumbers`() {
val allLowerExample = "aa"
val validator = Validator().checkNoNumbers()
whenever(editable.toString()).thenReturn(allLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkNoNumbers`() {
val oneSpecialCharExample = "s234_"
val validator = Validator().checkNoNumbers()
whenever(editable.toString()).thenReturn(oneSpecialCharExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkDoesNotContain`() {
val allLowerExample = "aa"
val validator = Validator().checkDoesNotContain("b")
whenever(editable.toString()).thenReturn(allLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkDoesNotContain`() {
val allLowerExample = "aa"
val validator = Validator().checkDoesNotContain("a")
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkContains`() {
val allLowerExample = "aa"
val validator = Validator().checkContains("a")
whenever(editable.toString()).thenReturn(allLowerExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkContains`() {
val allLowerExample = "aa"
val validator = Validator().checkContains("b")
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkContainsAtMostOne`() {
val containtsOneExample = "aab"
val validator = Validator().checkContainsAtMostOne('b')
whenever(editable.toString()).thenReturn(containtsOneExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkContainsAtMostOne`() {
val allLowerExample = "aa"
val validator = Validator().checkContainsAtMostOne('a')
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkEndsWith`() {
val endsWithExample = "aab"
val validator = Validator().checkEndsWith("ab")
whenever(editable.toString()).thenReturn(endsWithExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkEndsWith`() {
val allLowerExample = "aa"
val validator = Validator().checkEndsWith("b")
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkStartsWith`() {
val endsWithExample = "aab"
val validator = Validator().checkStartWith("aa")
whenever(editable.toString()).thenReturn(endsWithExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkStartsWith`() {
val allLowerExample = "aa"
val validator = Validator().checkStartWith("b")
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkForStandardPassword`() {
val standardPasswordExample = "<PASSWORD>"
val validator = Validator().checkForStandardPassword()
whenever(editable.toString()).thenReturn(standardPasswordExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkForStandardPassword`() {
val allLowerExample = "aa"
val validator = Validator().checkForStandardPassword()
whenever(editable.toString()).thenReturn(allLowerExample)
assertFalse(validator.validate(editText))
}
@Test
fun `success case with checkMatchesRegex`() {
val standardPasswordExample = "<PASSWORD>"
val validator = Validator().checkMatchesRegex(Regex("^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%^&+=_]).*\$"))
whenever(editable.toString()).thenReturn(standardPasswordExample)
assertTrue(validator.validate(editText))
}
@Test
fun `failure case with checkMatchesRegex`() {
val nonStandardPasswordExample = "<PASSWORD>"
val validator = Validator().checkMatchesRegex(Regex("^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%^&+=_]).*\$"))
whenever(editable.toString()).thenReturn(nonStandardPasswordExample)
assertFalse(validator.validate(editText))
}
}
| 0 |
Kotlin
|
0
| 4 |
e6817000993d1f41090ad3a57b951b0827b55e0b
| 13,398 |
svalidate
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.