How to use String.toByteArray method of org.spekframework.spek2.runtime.util.Base64 class

Best Spek code snippet using org.spekframework.spek2.runtime.util.Base64.String.toByteArray

SdpKanalITSpek.kt

Source:SdpKanalITSpek.kt Github

copy

Full Screen

1package no.nav.kanal.camel2import com.fasterxml.jackson.module.kotlin.readValue3import com.jcraft.jsch.ChannelSftp4import com.nhaarman.mockitokotlin2.argThat5import com.nhaarman.mockitokotlin2.reset6import com.nhaarman.mockitokotlin2.spy7import com.nhaarman.mockitokotlin2.timeout8import com.nhaarman.mockitokotlin2.verify9import com.nhaarman.mockitokotlin2.whenever10import io.ktor.application.call11import io.ktor.application.install12import io.ktor.features.ContentNegotiation13import io.ktor.jackson.jackson14import io.ktor.response.respond15import io.ktor.routing.post16import io.ktor.routing.routing17import io.ktor.server.cio.CIO18import io.ktor.server.engine.embeddedServer19import no.difi.begrep.sdp.schema_v10.SDPKvittering20import no.difi.begrep.sdp.schema_v10.SDPMelding21import no.digipost.api.representations.EbmsOutgoingMessage22import no.nav.kanal.ArchiveResponse23import no.nav.kanal.ConnectionPool24import no.nav.kanal.LegalArchiveLogger25import no.nav.kanal.config.SdpConfiguration26import no.nav.kanal.config.SdpKeys27import no.nav.kanal.config.VaultCredentials28import no.nav.kanal.config.VirksomhetssertifikatCredentials29import no.nav.kanal.createCamelContext30import no.nav.kanal.objectMapper31import org.amshove.kluent.any32import org.amshove.kluent.mock33import org.amshove.kluent.shouldBeGreaterOrEqualTo34import org.amshove.kluent.shouldBeInstanceOf35import org.amshove.kluent.shouldContain36import org.amshove.kluent.shouldEqual37import org.amshove.kluent.shouldNotEqual38import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl39import org.apache.activemq.artemis.core.server.ActiveMQServers40import org.apache.commons.io.IOUtils41import org.oasis_open.docs.ebxml_msg.ebms.v3_0.ns.core._200704.SignalMessage42import org.oasis_open.docs.ebxml_msg.ebms.v3_0.ns.core._200704.UserMessage43import org.spekframework.spek2.Spek44import org.spekframework.spek2.style.specification.describe45// TODO: Remove import and reenable tests46import org.spekframework.spek2.style.specification.xdescribe47import org.unece.cefact.namespaces.standardbusinessdocumentheader.StandardBusinessDocument48import java.io.StringReader49import java.net.ServerSocket50import java.nio.file.Files51import java.nio.file.Paths52import java.util.Base6453import java.util.UUID54import java.util.concurrent.TimeUnit55import java.util.concurrent.locks.ReentrantReadWriteLock56import javax.jms.BytesMessage57import javax.jms.ConnectionFactory58import javax.jms.TextMessage59import javax.naming.InitialContext60import javax.xml.bind.JAXBContext61import kotlin.concurrent.write62fun randomPort() = ServerSocket(0).use {63 it.localPort64}65val sdpMockPort: Int = randomPort()66val legalArchiveMockPort = randomPort()67open class QueuedReceiptHandler : SbdHandler {68 val receipts: MutableMap<String, EbmsResponse> = mutableMapOf()69 val userMessageHandlers = mutableListOf<()->EbmsResponse>()70 private val reentrantReadWriteLock: ReentrantReadWriteLock = ReentrantReadWriteLock()71 override fun handleUserMessage(sbdIn: StandardBusinessDocument, attachments: List<EbmsAttachment>, senderOrgNumber: String, userMessage: UserMessage): EbmsResponse {72 // Assume its a request to send SDP73 if (userMessageHandlers.isEmpty())74 return EbmsResponse(null, null, true, listOf())75 return reentrantReadWriteLock.write {76 userMessageHandlers.removeAt(0)()77 }78 }79 override fun handleSignalMessage(attachments: List<EbmsAttachment>, senderOrgNumber: String, signalMessage: SignalMessage): EbmsResponse = reentrantReadWriteLock.write {80 if (signalMessage.pullRequest != null && receipts.containsKey(signalMessage.pullRequest.mpc)) {81 return receipts.remove(signalMessage.pullRequest.mpc)!!82 }83 DefaultSbdHandler.noNewMessages()84 }85}86object SdpKanalITSpek : Spek({87 System.setProperty("javax.xml.soap.SAAJMetaFactory", "com.sun.xml.messaging.saaj.soap.SAAJMetaFactoryImpl")88 val activeMQServer = ActiveMQServers.newActiveMQServer(ConfigurationImpl()89 .setPersistenceEnabled(false)90 .setJournalDirectory("target/data/journal")91 .setSecurityEnabled(false)92 .addAcceptorConfiguration("invm", "vm://0"))93 activeMQServer.start()94 val keyStore = generateKeyStore().apply {95 Files.newOutputStream(Paths.get("build/keystore.p12")).use {96 store(it, "changeit".toCharArray())97 }98 Base64.getEncoder().wrap(Files.newOutputStream(Paths.get("build/keystore.p12.b64"))).use {99 store(it, "changeit".toCharArray())100 }101 }102 val requestHandler = spy(QueuedReceiptHandler())103 fun initSdpServer() = createSDPMockServer(sbdHandler = requestHandler, port = sdpMockPort, keyStore = keyStore)104 var sdpServer = initSdpServer()105 val vaultCredentials: VaultCredentials = objectMapper.readValue(VaultCredentials::class.java.getResourceAsStream("/vault.json"))106 val virksomhetssertifikatCredentials: VirksomhetssertifikatCredentials = objectMapper.readValue(VaultCredentials::class.java.getResourceAsStream("/virksomhet.json"))107 val config = SdpConfiguration(108 knownHostsFile = "TODO",109 ebmsEndpointUrl = "http://localhost:$sdpMockPort/sdpmock",110 mqHostname = "UNUSED",111 mqPort = -1,112 mqQueueManager = "UNUSED",113 mqChannel = "UNUSED",114 inputQueueNormal = "sdp_input_normal",115 inputQueuePriority = "sdp_input_priority",116 inputQueueNormalBackout = "sdp_input_normal_boq",117 inputQueuePriorityBackout = "sdp_input_priority_boq",118 receiptQueueNormal = "sdp_receipt_normal",119 receiptQueuePriority = "sdp_receipt_priority",120 keystorePath = "build/keystore.p12.b64",121 keystoreCredentialsPath = "UNUSED",122 truststorePath = "build/keystore.p12.b64",123 mqConcurrentConsumers = 4,124 receiptPollIntervalNormal = 1000,125 legalArchiveUrl = "http://localhost:$legalArchiveMockPort/upload",126 sdpCheckRevocation = false,127 sftpUrl = "UNUSED"128 )129 val requestMock = mock<() -> Any>()130 // TODO: Use mock engine whenever it supports JSON131 val legalArchiveMock = embeddedServer(CIO, port = legalArchiveMockPort) {132 install(ContentNegotiation) {133 jackson { }134 }135 routing {136 post("/upload") {137 call.respond(requestMock())138 }139 }140 }.start()141 val legalArchiveLogger = LegalArchiveLogger(config.legalArchiveUrl, "user", "pass")142 val sdpKeys = SdpKeys(config.keystorePath, config.truststorePath, virksomhetssertifikatCredentials, vaultCredentials, config.sdpCheckRevocation)143 val certBytes = sdpKeys.truststore.getCertificate("posten").encoded144 // Certificates are double base64 encoded145 val certB64 = Base64.getEncoder().encode(certBytes)146 val appCert = Base64.getEncoder().encodeToString(certB64)147 val connectionFactory = InitialContext().lookup("ConnectionFactory") as ConnectionFactory148 val queueConnection = connectionFactory.createConnection()149 queueConnection.start()150 val connectionPool = ConnectionPool({ mock(ChannelSftp::class) }, {})151 val camelContext = createCamelContext(config, sdpKeys, connectionFactory, connectionPool, legalArchiveLogger)152 camelContext.start()153 val session = queueConnection.createSession()154 val normalQueueSender = session.createProducer(session.createQueue(config.inputQueueNormal))155 val normalQueueConsumer = session.createConsumer(session.createQueue(config.inputQueueNormal))156 val priorityQueueSender = session.createProducer(session.createQueue(config.inputQueuePriority))157 val normalReceiptConsumer = session.createConsumer(session.createQueue(config.receiptQueueNormal))158 val priorityReceiptConsumer = session.createConsumer(session.createQueue(config.receiptQueuePriority))159 val normalBackoutConsumer = session.createConsumer(session.createQueue(config.inputQueueNormalBackout))160 val priorityBackoutConsumer = session.createConsumer(session.createQueue(config.inputQueuePriorityBackout))161 val messageBytes = IOUtils.toByteArray(SdpKanalITSpek::class.java.getResourceAsStream("/payloads/inline.xml"))162 fun shutdownServer() {163 sdpServer.server.stop()164 sdpServer.server.destroy()165 sdpServer.sfb.bus.shutdown(true)166 }167 afterEachTest {168 reset(requestHandler, requestMock)169 whenever(requestMock()).thenReturn(ArchiveResponse(id = 0))170 }171 afterGroup {172 legalArchiveMock.stop(10, 10, TimeUnit.SECONDS)173 camelContext.shutdown()174 queueConnection.close()175 shutdownServer()176 activeMQServer.stop(true)177 println("SHUTDOWN")178 }179 // TODO: I want something to help figure out if the route was completed successfully180 /*fun whenBodiesDone(content: String) = NotifyBuilder(camelContext)181 .fromRoute(SEND_NORMAL_ROUTE_NAME)182 .whenBodiesDone(content)183 .or()184 .fromRoute(SEND_PRIORITY_ROUTE_NAME)185 .whenBodiesDone(content)186 .create()*/187 fun genPayload(conversationId: String = UUID.randomUUID().toString()): String =188 messageBytes.toString(Charsets.UTF_8).replace("CONV_ID", conversationId).replace("B64_CERTIFICATE", appCert)189 xdescribe("Sending messages on the input queue") {190 listOf(normalQueueSender, priorityQueueSender).forEach {191 it("Results in the message dispatcher receiving the message from input queue ${it.destination}") {192 val payload = genPayload()193 //val notify = whenBodiesDone(payload)194 it.send(session.createTextMessage(payload))195 verify(requestHandler, timeout(20000).times(1)).handleUserMessage(any(), any(), any(), any())196 //notify.matches(10000, TimeUnit.MILLISECONDS) shouldEqual true197 }198 }199 }200 describe("Returning a receipt from the message dispatcher") {201 val normalMpc = "urn:${EbmsOutgoingMessage.Prioritet.NORMAL.value()}:${config.mpcNormal}"202 val priorityMpc = "urn:${EbmsOutgoingMessage.Prioritet.PRIORITERT.value()}:${config.mpcPrioritert}"203 listOf(normalMpc to normalReceiptConsumer, priorityMpc to priorityReceiptConsumer).forEach { (mpcId, receiptQueue) ->204 it("Returning a receipt with mpc $mpcId results in a receipt on the queue $receiptQueue") {205 val messageId = UUID.randomUUID().toString()206 println("UUID used for messageId $messageId")207 requestHandler.receipts[mpcId] = DefaultSbdHandler.defaultReceipt(messageId)208 val message = receiptQueue.receive(10000)209 message shouldBeInstanceOf BytesMessage::class210 message as BytesMessage211 val bytes = ByteArray(message.bodyLength.toInt())212 message.readBytes(bytes)213 val receipt = bytes.toString(Charsets.UTF_8)214 // The receipt should be able to get unmarshalled into a StandardBusinessDocument215 val sbdJaxbContext = JAXBContext.newInstance(StandardBusinessDocument::class.java, SDPMelding::class.java)216 val sbdUnmarshaller = sbdJaxbContext.createUnmarshaller()217 val sbd = sbdUnmarshaller.unmarshal(StringReader(receipt)) as StandardBusinessDocument218 sbd.any shouldNotEqual null219 sbd.any shouldBeInstanceOf SDPKvittering::class220 sbd.standardBusinessDocumentHeader.documentIdentification.instanceIdentifier shouldEqual messageId221 verify(requestHandler, timeout(20000).atLeast(1)).handleSignalMessage(any(), any(), argThat { this.receipt != null && !this.receipt.anies.isEmpty() })222 println("Received receipt $receipt")223 }224 }225 }226 xdescribe("SOAP fault from the message dispatcher") {227 listOf(normalQueueSender to normalBackoutConsumer, priorityQueueSender to priorityBackoutConsumer).forEach { (inputQueue, backoutQueue) ->228 it("Sending a message on the input queue ${inputQueue.destination} while exception is thrown ends up at $backoutQueue") {229 val payload = genPayload()230 //val notify = whenBodiesDone(payload)231 inputQueue.send(session.createTextMessage(payload))232 requestHandler.userMessageHandlers.add {233 throw RuntimeException("Integration test")234 }235 val message = backoutQueue.receive(10000)236 message shouldBeInstanceOf TextMessage::class237 message as TextMessage238 message.text shouldEqual payload239 //notify.matches(10000, TimeUnit.MILLISECONDS) shouldEqual true240 }241 }242 }243 xdescribe("In-flight messages") {244 it("In-flight messages get sent to BOQ whenever they can't reach the message dispatcher") {245 shutdownServer()246 val numberOfMessages = 100247 val inputMessages = 0.until(numberOfMessages).map { genPayload() }248 inputMessages.forEach { normalQueueSender.send(session.createTextMessage(it)) }249 // Let the route run for a second to make sure its in a transaction250 Thread.sleep(1000)251 camelContext.shutdown()252 val backoutMessages = 0.rangeTo(numberOfMessages*2)253 .map { normalBackoutConsumer.receiveNoWait() }254 .filterNotNull()255 .filter { it is TextMessage }256 val inputQueueMessages = 0.rangeTo(numberOfMessages*2)257 .map { normalQueueConsumer.receiveNoWait() }258 .filterNotNull()259 .filter { it is TextMessage }260 val messagesLeft = listOf(backoutMessages, inputQueueMessages).flatten()261 .map { it as TextMessage }262 .map { it.text }263 println("Done getting messages from queues, results: backout=${backoutMessages.size}, input=${inputQueueMessages.size}")264 backoutMessages.size shouldBeGreaterOrEqualTo config.mqConcurrentConsumers265 messagesLeft.size shouldBeGreaterOrEqualTo numberOfMessages266 inputMessages.forEach { messagesLeft shouldContain it }267 camelContext.start()268 sdpServer = initSdpServer()269 }270 }271 describe("Legal Archive logging") {272 it("Message should go through even regardless of message being logged to legal archive") {273 }274 }275})...

Full Screen

Full Screen

Base64.kt

Source:Base64.kt Github

copy

Full Screen

1package org.spekframework.spek2.runtime.util2actual object Base64 {3 actual fun encodeToString(text: String): String {4 return java.util.Base64.getEncoder().encodeToString(text.toByteArray())5 }6 actual fun decodeToString(encodedText: String): String {7 return String(8 java.util.Base64.getDecoder().decode(encodedText.toByteArray())9 )10 }11}...

Full Screen

Full Screen

String.toByteArray

Using AI Code Generation

copy

Full Screen

1val byteArray = "Hello".toByteArray()2val encodedString = Base64.encode(byteArray)3println(encodedString)4val decodedString = Base64.decode(encodedString)5println(decodedString)6val decodedString = "SGVsbG8=".fromBase64()7println(decodedString)8val encodedString = "Hello".toBase64()9println(encodedString)10val decodedString = "SGVsbG8=".fromBase64()11println(decodedString)12val decodedString = Base64.decode("SGVsbG8=")13println(decodedString)14val encodedString = Base64.encode("Hello".toByteArray())15println(encodedString)16val decodedString = Base64.decode("SGVsbG8=")17println(decodedString)18val encodedString = Base64.encode("Hello".toByteArray())19println(encodedString)

Full Screen

Full Screen

String.toByteArray

Using AI Code Generation

copy

Full Screen

1fun String.toByteArray() = Base64.decode(this)2fun String.fromByteArray() = Base64.encode(this)3fun String.toBase64() = Base64.encode(this)4fun String.fromBase64() = Base64.decode(this)5fun String.toMD5() = MD5.encode(this)6fun String.toSHA256() = SHA256.encode(this)7fun String.toSHA512() = SHA512.encode(this)8fun String.toSHA3_512() = SHA3_512.encode(this)9fun String.toSHA3_256() = SHA3_256.encode(this)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Spek automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful