本文整理汇总了Scala中javax.xml.bind.DatatypeConverter类的典型用法代码示例。如果您正苦于以下问题:Scala DatatypeConverter类的具体用法?Scala DatatypeConverter怎么用?Scala DatatypeConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DatatypeConverter类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: OverlayDemo
//设置package包名称以及导入依赖的类
package edu.uw.at.iroberts.wirefugue.protocol.overlay
trait Overlay
object OverlayDemo extends App {
import javax.xml.bind.DatatypeConverter
import akka.util.ByteString
// val packet0: ByteString = ByteString.fromInts(Array.fill(28)(scala.util.Random.nextInt() % 256): _*)
val packet: ByteString = ByteString.fromArray(
DatatypeConverter.parseHexBinary(
"010203040506" +
"111213141516" +
"0004" +
"2021222324252627282930313233343536373839"
)
)
val ethernet = Ethernet(packet)
println(ethernet.src)
println(ethernet.dst)
println(ethernet.etherType)
println(ethernet.payload)
ethernet.etherType match {
case 0x0004 =>
println(s"length: ${ethernet.payload.length}")
val ip4 = IPV4Datagram(ethernet.payload)
println(ip4.src)
println(ip4.dest)
case x =>
println(f"Expected 0x0004, got 0x$x%04x")
}
}
示例2: encodeHex
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter
import akka.stream.scaladsl.{Flow, Keep, Sink}
import akka.util.ByteString
import scala.concurrent.Future
package object auth {
def encodeHex(bytes: Array[Byte]): String = DatatypeConverter.printHexBinary(bytes).toLowerCase
def encodeHex(bytes: ByteString): String = encodeHex(bytes.toArray)
def digest(algorithm: String = "SHA-256"): Sink[ByteString, Future[ByteString]] =
Flow[ByteString]
.fold(MessageDigest.getInstance(algorithm)) {
case (digest, bytes) =>
digest.update(bytes.asByteBuffer)
digest
}
.map(d => ByteString(d.digest()))
.toMat(Sink.head[ByteString])(Keep.right)
}
示例3: PrepareFile
//设置package包名称以及导入依赖的类
import com.example.protos.demo.{Address, Person, Gender}
import javax.xml.bind.DatatypeConverter
object PrepareFile {
val persons = Seq(
Person().update(
_.name := "Joe",
_.age := 32,
_.gender := Gender.MALE),
Person().update(
_.name := "Mark",
_.age := 21,
_.gender := Gender.MALE,
_.addresses := Seq(
Address(city = Some("San Francisco"), street=Some("3rd Street"))
)),
Person().update(
_.name := "Steven",
_.age := 35,
_.gender := Gender.MALE,
_.addresses := Seq(
Address(city = Some("San Francisco"), street=Some("5th Street")),
Address(city = Some("Sunnyvale"), street=Some("Wolfe"))
)),
Person().update(
_.name := "Batya",
_.age := 11,
_.gender := Gender.FEMALE))
def main(args: Array[String]) {
persons.foreach {
p =>
println(DatatypeConverter.printBase64Binary(p.toByteArray))
}
}
}
示例4: SystemUtil
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.util
import java.io.File
import java.io.FileInputStream
import java.security.DigestInputStream
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter
object SystemUtil {
private val BUF_SIZE: Int = 0x1000
def md5(file: File): Array[Byte] = {
val md = MessageDigest.getInstance("MD5")
val is = new FileInputStream(file)
try {
val dis = new DigestInputStream(is, md)
try {
val buf: Array[Byte] = new Array[Byte](BUF_SIZE)
while (dis.read(buf) != -1) {}
} finally {
dis.close()
}
} finally {
is.close()
}
md.digest()
}
def base64Md5(file: File): String = DatatypeConverter.printBase64Binary(md5(file))
}
示例5: JWTUtils
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.util
import io.jsonwebtoken.Jwts
import java.nio.charset.StandardCharsets
import javax.xml.bind.DatatypeConverter
object JWTUtils {
case class User(name:String, admin:Boolean)
val adminToken = "eyJhbGciOiJIUzUxMiJ9.eyJuYW1lIjoiYWRtaW4iLCJhZG1pbiI6dHJ1ZX0.c6wRZ4pla6D9f_nDO6tqwyq5KFwyW2iSkKvrwGejn2IMxU_Z273cKZAW3Fu51Cwhp-4vwqOr1aWnyUIwzb_eow"
val myToken = "eyJhbGciOiJIUzUxMiJ9.eyJuYW1lIjoiU2hhc2hhbmsiLCJhZG1pbiI6ZmFsc2V9.smlXLOZFZ14fozEwULbiSvzDEStlVjnLWSmg6MiaDDXUirCJjPpkNrzpKI31MxID0ZUV-H3tEcPmB9jJjGl9qA"
private val secretKey = DatatypeConverter.printBase64Binary("introductiontoakkahttp".getBytes(StandardCharsets.UTF_8))
def decodeJWTToUser(tokenString:String):Option[User] = {
try {
val claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(tokenString).getBody
Some(User(claims.get("name").asInstanceOf[String], claims.get("admin").asInstanceOf[Boolean]))
} catch {
case e : Exception => {
println("exception in decode token: " + e.getMessage())
println("Considering it as invalid token")
None
}
}
}
}
示例6: SessionUtil
//设置package包名称以及导入依赖的类
package com.softwaremill.session
import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import javax.xml.bind.DatatypeConverter
object SessionUtil {
def randomString(length: Int) = {
// http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
val random = ThreadLocalRandom.current()
new BigInteger(length * 5, random).toString(32) // because 2^5 = 32
}
def randomServerSecret() = randomString(128)
// Do not change this unless you understand the security issues behind timing attacks.
// This method intentionally runs in constant time if the two strings have the same length.
// If it didn't, it would be vulnerable to a timing attack.
def constantTimeEquals(a: String, b: String) = {
if (a.length != b.length) {
false
}
else {
var equal = 0
for (i <- Array.range(0, a.length)) {
equal |= a(i) ^ b(i)
}
equal == 0
}
}
def toHexString(array: Array[Byte]): String = {
DatatypeConverter.printHexBinary(array)
}
def hexStringToByte(hexString: String): Array[Byte] = {
DatatypeConverter.parseHexBinary(hexString)
}
}
示例7: Crypto
//设置package包名称以及导入依赖的类
package com.softwaremill.session
import java.security.MessageDigest
import java.util
import javax.crypto.{Cipher, Mac}
import javax.crypto.spec.SecretKeySpec
import javax.xml.bind.DatatypeConverter
import com.softwaremill.session.SessionUtil._
object Crypto {
def sign_HmacSHA1_hex(message: String, secret: String): String = {
val key = secret.getBytes("UTF-8")
val mac = Mac.getInstance("HmacSHA1")
mac.init(new SecretKeySpec(key, "HmacSHA1"))
toHexString(mac.doFinal(message.getBytes("utf-8")))
}
def sign_HmacSHA256_base64(message: String, secret: String): String = {
val key = secret.getBytes("UTF-8")
val mac = Mac.getInstance("HmacSHA256")
mac.init(new SecretKeySpec(key, "HmacSHA256"))
DatatypeConverter.printBase64Binary(mac.doFinal(message.getBytes("utf-8")))
}
def encrypt_AES(value: String, secret: String): String = {
val raw = util.Arrays.copyOf(secret.getBytes("utf-8"), 16)
val skeySpec = new SecretKeySpec(raw, "AES")
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
toHexString(cipher.doFinal(value.getBytes("utf-8")))
}
def decrypt_AES(value: String, secret: String): String = {
val raw = util.Arrays.copyOf(secret.getBytes("utf-8"), 16)
val skeySpec = new SecretKeySpec(raw, "AES")
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, skeySpec)
new String(cipher.doFinal(hexStringToByte(value)))
}
def hash_SHA256(value: String): String = {
val digest = MessageDigest.getInstance("SHA-256")
toHexString(digest.digest(value.getBytes("UTF-8")))
}
}
示例8: DocxMetadataWriter
//设置package包名称以及导入依赖的类
package anchorman.docx
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter
import anchorman.core.Document
import anchorman.media._
import scala.xml.NodeSeq
class DocxMetadataWriter {
val documentRelId: String =
"rDocument"
val numberingRelId: String =
"rNumbering"
val stylesRelId: String =
"rStyles"
def mediaRelId(url: String): String = {
val digest = MessageDigest.getInstance("MD5")
digest.update(url.getBytes)
"rMedia" + DatatypeConverter.printHexBinary(digest.digest()).toUpperCase
}
def writeContentTypes(doc: Document): NodeSeq =
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default ContentType="application/xml" Extension="xml"/>
<Default ContentType="image/jpeg" Extension="jpg"/>
<Default ContentType="image/png" Extension="png"/>
<Default ContentType="image/x-emf" Extension="emf"/>
<Default ContentType="application/vnd.openxmlformats-package.relationships+xml" Extension="rels"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" PartName="/word/document.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml" PartName="/word/numbering.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" PartName="/word/styles.xml"/>
</Types>
def writeRootRels(doc: Document): NodeSeq =
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id={documentRelId} Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>
def writeDocumentRels(doc: Document, media: Seq[MediaFile]): NodeSeq = {
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id={numberingRelId} Target="numbering.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"/>
<Relationship Id={stylesRelId} Target="styles.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"/>
{
media.map { file =>
<Relationship Id={file.relId} Target={"media/" + file.filename} Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"/>
}
}
</Relationships>
}
}
示例9: sanitize
//设置package包名称以及导入依赖的类
package controllers
import java.security.SecureRandom
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.{PBEKeySpec}
import javax.xml.bind.DatatypeConverter
def sanitize(s:Array[Byte]): String = {
DatatypeConverter.printBase64Binary(s)
}
def hash(password: Array[Char], salt: Array[Byte], iterations: Int): String = {
val spec = new PBEKeySpec(password, salt, iterations, Math.min(160, salt.length*8))
val skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
sanitize(skf.generateSecret(spec).getEncoded)
}
def generateSalt(length: Int): String = {
val saltBuf = new Array[Byte] (length)
val rng = new SecureRandom()
rng.nextBytes(saltBuf)
sanitize(saltBuf)
}
def generateKey(password: String, iterations: Int, saltLength: Int): (String, String) = {
val salt = generateSalt(saltLength)
val hash = this.hash(password.toCharArray, salt.getBytes("UTF-8"), iterations)
(hash, salt)
}
}
示例10: Decompiler
//设置package包名称以及导入依赖的类
package io.github.jamespic.ethereum_tools.decompiler
import java.nio.file.{Files, Paths}
import java.nio.charset.StandardCharsets.UTF_8
import javax.xml.bind.DatatypeConverter
import org.ethereum.util.blockchain.StandaloneBlockchain
import io.github.jamespic.ethereum_tools.Bytecode
import io.github.jamespic.ethereum_tools.decompiler.control_flow.{Block, ControlGraph, GraphRewriteRules, Func}
object Decompiler {
def main(args: Array[String]) = {
val bytecode = args match {
case Array("--solidity", x, name) =>
val code = new String(Files.readAllBytes(Paths.get(x)), UTF_8)
val blockchain = new StandaloneBlockchain().withAutoblock(true)
try {
val contract = blockchain.submitNewContract(code, name)
val contractAddress = contract.getAddress()
blockchain.getBlockchain().getRepository().getCode(contractAddress)
} finally blockchain.getBlockchain().close()
case Array("--bytecode", x) =>
val code = new String(Files.readAllBytes(Paths.get(x)), UTF_8).trim
DatatypeConverter.parseHexBinary(code)
}
println(decompile(bytecode))
}
def decompile(bytes: Array[Byte]) = {
val instructions = Bytecode.parse(bytes)
val blocks = Block.identifyBasicBlocks(instructions)
val controlGraph = ControlGraph(blocks)
val rewritten = GraphRewriteRules.stripUnreachable(controlGraph).getOrElse(controlGraph)
println(Func.identifyFunctionsByReturn(rewritten))
rewritten
}
}
示例11: Util
//设置package包名称以及导入依赖的类
package org.pgscala.embedded
import java.net.{ConnectException, Socket}
import java.security.MessageDigest
import java.util.Locale
import javax.xml.bind.DatatypeConverter
import com.typesafe.scalalogging.StrictLogging
object Util extends StrictLogging {
def bin2Hex(binary: Array[Byte]): String =
DatatypeConverter.printHexBinary(binary).toLowerCase(Locale.ROOT)
def digest(text: String): Array[Byte] = {
val md = MessageDigest.getInstance("SHA-256")
md.digest(text.getBytes("UTF-8"))
}
lazy val isWindows: Boolean = OS.Name.resolved match {
case Some(OS.Name.Windows) => true
case _ => false
}
lazy val isUnix: Boolean = OS.Name.resolved match {
case Some(OS.Name.Linux) | Some(OS.Name.OSX) => true
case _ => false
}
private[this] def socketIsFree(host: String, port: Int): Boolean =
try {
logger.trace(s"Checking if port $port is free...")
new Socket(host, port).close()
logger.debug(s"Port $port is free, choosing it for the cluster")
false
} catch {
case _: ConnectException =>
true
}
def findFreePort(host: String, portRange: Range): Int =
portRange.find(port => socketIsFree(host, port))
.getOrElse(sys.error(s"Could not find free port in range: [${portRange.head},${portRange.last}]"))
}
示例12: SqlOps
//设置package包名称以及导入依赖的类
package effectful.examples.pure.dao.sql.impl
import java.time.format.DateTimeFormatter
import javax.xml.bind.DatatypeConverter
import effectful.examples.effects.sql.SqlVal
import effectful.examples.effects.sql.SqlVal._
import effectful.examples.pure.dao.sql.SqlString
object SqlOps {
def printSql(sqlVal: SqlVal) : SqlString = SqlString {
def quotes(s: String) = s"'$s'"
sqlVal match {
case NULL(_) => "null"
case CHAR(_,data) => quotes(data.toCharString())
case VARCHAR(_,data) => quotes(data.toCharString())
case NCHAR(_,data) => quotes(data.toCharString())
case NVARCHAR(_,data) => quotes(data.toCharString())
// todo: prob shouldn't ship these as strings - should be way to attach stream?
case CLOB(data) => quotes(data.toCharString())
case NCLOB(data) => quotes(data.toCharString())
// todo: possible to use base 64 instead of hex for binary? more efficient
case BINARY(_,data) => DatatypeConverter.printHexBinary(data.toByteArray())
case VARBINARY(_,data) => DatatypeConverter.printHexBinary(data.toByteArray())
case BLOB(data) => DatatypeConverter.printHexBinary(data.toByteArray())
case BOOLEAN(value) => if(value) "true" else "false"
case BIT(value) => if(value) "1" else "0"
case TINYINT(value) => value.toString
case SMALLINT(value) => value.toString
case INTEGER(value) => value.toString
case BIGINT(value) => value.toString
case REAL(value) => value.toString
case DOUBLE(value) => value.toString
case NUMERIC(value,_,_) => value.toString
case DECIMAL(value,_,_) => value.toString
case DATE(date) => quotes(DateTimeFormatter.ISO_DATE.format(date))
case TIME(time) => quotes(DateTimeFormatter.ISO_TIME.format(time))
case TIMESTAMP(timestamp) => quotes(DateTimeFormatter.ISO_INSTANT.format(timestamp))
}
}
}