kotlin 在字典中搜索单词

在字典中搜索单词

DictionaryRepository.kt
val findSpec = SqlQuerySpec().apply {
                queryText = "SELECT Dictionary.word AS word, Dictionary.meaning AS meaning FROM Dictionary WHERE Dictionary.partition = @tag AND contains(Dictionary.search, @query) OFFSET @offset LIMIT @records_per_page"
                parameters = SqlParameterCollection().apply {
                    add(SqlParameter("@tag", query.first().toUpperCase().toString()))
                    add(SqlParameter("@query", query.toLowerCase()))
                    add(SqlParameter("@offset", offset))
                    add(SqlParameter("@records_per_page", RECORDS_PER_PAGE))
                }
            }
val countSpec = SqlQuerySpec().apply {
                queryText = "SELECT COUNT(1) AS TotalRecords FROM Dictionary WHERE Dictionary.partition = @tag AND contains(Dictionary.search, @query)"
                parameters = SqlParameterCollection().apply {
                    add(SqlParameter("@tag", query.first().toUpperCase().toString()))
                    add(SqlParameter("@query", query.toLowerCase()))
                }
            }

kotlin 字典存储库

字典存储库

DictionaryRepository.kt
class DictionaryRepository : RepositoryInterface, KoinComponent {
    companion object {
        val RECORDS_PER_PAGE = 20
    }

    val client: DocumentClient by inject()

    override fun getNumberOfPagesInDictionary(): Page {
        var page: Page
        try {
            val document = client.queryDocuments(
                    System.getenv("COLLECTION_URI"),
                    "SELECT Dictionary.total AS TotalRecords FROM Dictionary WHERE Dictionary.partition = 'atoz' AND Dictionary.total > 0", null).queryIterable.first()
            val total = document.getInt("TotalRecords")
            val endPage = ceil(total.toFloat() / RECORDS_PER_PAGE.toFloat()).toInt()
            page = Page(1, endPage, RECORDS_PER_PAGE)
        } catch (e: Exception) {
            throw PageRetrievalException(e.message ?: "Unable to retrieve data")
        }
        return page
    }
}

kotlin Azure Cosmos数据库连接

Azure Cosmos数据库连接

Startup.kt
object Startup {
    var dictionary: Module = module(override = true) {
        single { api.data.repository.DictionaryRepository() as api.data.repository.RepositoryInterface }
        single {
            com.microsoft.azure.documentdb.DocumentClient(java.lang.System.getenv("HOST"),
                    System.getenv("MASTER_KEY"),
                    com.microsoft.azure.documentdb.ConnectionPolicy.GetDefault(),
                    com.microsoft.azure.documentdb.ConsistencyLevel.Session)
        }
    }

    init {
        injectDependencies()
    }
}


fun injectDependencies() {
    startKoin { modules(Startup.dictionary) }
}

kotlin 字典处理程序测试

字典处理程序测试

DictionaryHandlerTest.kt
class DictionaryHandlerTest {

    @Test
    fun testGetTotalPagesInDictionary() {
        val handler = DictionaryTotalPageHandler()
        val gson = Gson()
        loadKoinModules(module(override = true) {
            single { MockRepository() as RepositoryInterface }
        })

        val req = mock(HttpRequestMessage::class.java)

        val context = mock(ExecutionContext::class.java)
        doReturn(Logger.getGlobal()).`when`(context).logger
        doAnswer { invocation ->
            val status = invocation.arguments[0] as HttpStatus
            HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status)
        }.`when`(req).createResponseBuilder(any(HttpStatus::class.java))

        val ret = handler.run(req as HttpRequestMessage<Optional<String>>, context)
        val body = ret.body.toString()
        val result = gson.fromJson(body, Page::class.java)
        assertEquals(1, result.start)
        assertEquals(3, result.end)
        assertEquals(10, result.recordsPerPage)
        assertEquals(ret.status, HttpStatus.OK)
    }

    @Test
    fun testGetTotalPagesInDictionary_withError() {
        val handler = DictionaryTotalPageHandler()
        val repository = mock(RepositoryInterface::class.java)
        val gson = Gson()
        // Setup
        loadKoinModules(module(override = true) {
            single { repository }
        })

        val req = mock(HttpRequestMessage::class.java)

        doReturn(URI("v1/dictionary/pages")).`when`(req).uri

        val context = mock(ExecutionContext::class.java)
        doReturn(Logger.getGlobal()).`when`(context).logger
        doAnswer { invocation ->
            val status = invocation.arguments[0] as HttpStatus
            HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status)
        }.`when`(req).createResponseBuilder(any(HttpStatus::class.java))

        doAnswer {
            throw PageRetrievalException("error")
        }.`when`(repository).getNumberOfPagesInDictionary()

        val ret = handler.run(req as HttpRequestMessage<Optional<String>>, context)
        val body = ret.body.toString()
        val result = gson.fromJson(body, ErrorMesssage::class.java)
        assertEquals("error", result.message)
        assertEquals("v1/dictionary/pages", result.path)
    }
    
}

kotlin 字典控制器

字典控制器

DictionaryController.kt
class DictionaryController : KoinComponent {

    private val repository: RepositoryInterface by inject()

    fun getNumberOfPagesInDictionary(): Any {
        return try {
            repository.getNumberOfPagesInDictionary()
        } catch (e: PageRetrievalException) {
            ErrorMesssage(message = e.errorMessage, type = ErrorType.PAGE_RETRIVAL_ERROR)
        }
    }
    
}

kotlin 依赖注入

依赖注入

Startup.kt
object Startup {
    var dictionary: Module = module(override = true) {
        single { ... }
    }

    init {
        injectDependencies()
    }
}


fun injectDependencies() {
    startKoin { modules(Startup.dictionary) }
}

kotlin 获取字典中的总页数

获取字典中的总页数

DictionaryTotalPageHandler.kt
class DictionaryTotalPageHandler {

    private val global = Startup

    @FunctionName("getNumberOfPagesInDictionary")
    fun run(
            @HttpTrigger(name = "req", methods = [HttpMethod.GET], route = "v1/dictionary/pages", authLevel = AuthorizationLevel.ANONYMOUS) request: HttpRequestMessage<Optional<String>>,
            context: ExecutionContext): HttpResponseMessage {
        context.logger.info("Processing get pages of dictionary")
        val result = DictionaryController().getNumberOfPagesInDictionary()
        return getResponse(request, result)
    }
}

kotlin 设置用户可读性

BaseDaoWithAbilityToSetUserReadProperty
    override fun setElements(elements: List<TModel>): Observable<List<TModel>> {
        return ENTITY.executeTransaction {
            if (!elements.isNullOrEmpty()) {
                elementsAlreadyReadByUser = ENTITY.query {
                    equalTo("readByUser", true)
                }.map { it.id!! }
                ENTITY.delete {
                    equalTo("profileId", elements.first().profileId)
                }
            }
            elements.apply {
                forEach { element ->
                    val realmModel = element.modelToRealmModel()
                    if (elementsAlreadyReadByUser.contains(element.id)) {
                        realmModel.readByUser = true
                    }
                    realmModel.save()
                }
            }
        }
    }

kotlin 抽象类

一个类,其对象无法创建,但可以作为继承的基类。 <br/> <br/>抽象类和接口之间的区别在于接口不能有构造函数。 <br/> <br/>使用Interface定义的对象只能调用接口内的Function。

abstract.kt
abstract class abc()
{
    abstract val pqr: String
}

class xyz : abc(), FishAction
{
    override val pqr = "something"
    override fun eat()
        {
            print ("using interface")
        }
}

interface FishAction()
{
    fun eat()    
}


main()
{
 // Objects passed through anyname will only be able to access Interface Functions.
    fun onlyaccessinterface(anyname: FishAction)       
        {
            anyname.eat()
        }
}

kotlin 遗产

inheritance.kt
// Open keyword makes class / members inheritable

open class abc()
    {
        open var x = 10
    }
    
class xyz() : abc()
    {
        override var x = 12
        //Can also override functions
    }