├── project ├── build.properties └── plugins.sbt ├── .scalafmt.conf ├── .github ├── release-drafter.yml └── workflows │ └── ci.yml ├── .gitignore ├── core └── src │ ├── main │ └── scala │ │ └── com │ │ └── softwaremill │ │ └── id │ │ ├── pretty │ │ ├── StringIdGenerator.scala │ │ ├── Codec.scala │ │ ├── Damm.scala │ │ └── IdPrettyfier.scala │ │ └── IdGenerator.scala │ └── test │ └── scala │ └── com │ └── softwaremill │ └── id │ ├── pretty │ ├── AlphabetCodecSpec.scala │ ├── DammSpec.scala │ ├── ExampleSpec.scala │ ├── IdPrettifierBenchmarkSpec.scala │ └── IdPrettifierSpec.scala │ └── DefaultIdGeneratorSpec.scala ├── scripts └── decrypt_files_if_not_pr.sh ├── README.md └── LICENSE /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.6.2 -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | runner.dialect = scala3 2 | version = 3.5.2 3 | maxColumn = 120 -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | template: | 2 | ## What’s Changed 3 | 4 | $CHANGES -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | .cache 5 | .history 6 | .lib/ 7 | dist/* 8 | target/ 9 | lib_managed/ 10 | src_managed/ 11 | project/boot/ 12 | project/plugins/project/ 13 | 14 | .idea* 15 | -------------------------------------------------------------------------------- /core/src/main/scala/com/softwaremill/id/pretty/StringIdGenerator.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | trait StringIdGenerator { 4 | def nextId(): String 5 | 6 | def idBaseAt(timestamp: Long): String 7 | } 8 | -------------------------------------------------------------------------------- /scripts/decrypt_files_if_not_pr.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then 4 | openssl aes-256-cbc -K $encrypted_efb718960ce9_key -iv $encrypted_efb718960ce9_iv -in secrets.tar.enc -out secrets.tar -d 5 | tar xvf secrets.tar 6 | fi 7 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.9.0") 2 | 3 | val sbtSoftwareMillVersion = "2.0.9" 4 | addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion) 5 | addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion) 6 | 7 | addSbtPlugin("org.jetbrains" % "sbt-ide-settings" % "1.1.0") 8 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/pretty/AlphabetCodecSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import org.scalatest.flatspec.AnyFlatSpec 4 | import org.scalatest.matchers.should.Matchers 5 | 6 | class AlphabetCodecSpec extends AnyFlatSpec with Matchers { 7 | val codec = new AlphabetCodec(Alphabet.Base23) 8 | behavior of codec.getClass.getSimpleName 9 | 10 | val max = Long.MaxValue 11 | val exampleId = 824227036833910784L 12 | 13 | it should "encode value" in { 14 | import codec._ 15 | encode(23) should be("BA") 16 | encode(529) should be("BAA") 17 | encode(12167) should be("BAAA") 18 | } 19 | 20 | it should "decode value" in { 21 | import codec._ 22 | decode("BA") should be(23) 23 | decode("ABA") should be(23) 24 | decode("BAA") should be(529) 25 | decode("BAB") should be(530) 26 | decode("BAAA") should be(12167) 27 | decode("HAPK") should be(85477) 28 | decode("HPJD") should be(92233) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/pretty/DammSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import org.scalatest.flatspec.AnyFlatSpec 4 | import org.scalatest.matchers.should.Matchers 5 | 6 | class DammSpec extends AnyFlatSpec with Matchers { 7 | behavior of Damm.getClass.getSimpleName 8 | 9 | val max = Long.MaxValue 10 | 11 | it should "calculate check digit" in { 12 | val withChecksum = Damm(max.toString) 13 | 14 | Damm.isValid(withChecksum) should be(true) 15 | } 16 | 17 | it should "fail on checking check digit" in { 18 | val withChecksum = Damm(max.toString) 19 | 20 | (0 until withChecksum.length).foreach { i => 21 | val sb = new StringBuilder(withChecksum) 22 | val oldChar = sb.charAt(i).toString.toInt 23 | val newChar = ((oldChar + 1) % 10).toString 24 | sb.setCharAt(i, newChar.toCharArray.head) 25 | val corrupted = sb.toString() 26 | Damm.isValid(corrupted) should be(false) 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /core/src/main/scala/com/softwaremill/id/pretty/Codec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import scala.annotation.tailrec 4 | import scala.math.pow 5 | 6 | trait Codec { 7 | 8 | def encode(number: Long): String 9 | 10 | def decode(value: String): Long 11 | } 12 | 13 | class AlphabetCodec(alphabet: Alphabet) extends Codec { 14 | 15 | def encode(number: Long): String = encode(number, "") 16 | 17 | @tailrec 18 | private def encode(number: Long, rest: String): String = { 19 | val modulo: Int = (number % alphabet.base).toInt 20 | val result = alphabet.valueOf(modulo).toString + rest 21 | if (number < alphabet.base) { 22 | result 23 | } else { 24 | encode(number / alphabet.base, result) 25 | } 26 | } 27 | 28 | def decode(value: String): Long = { 29 | case class ResultWithIndex(result: Long, index: Int) 30 | value 31 | .foldRight(ResultWithIndex(0, 0)) { (c, resultWithIndex) => 32 | ResultWithIndex( 33 | resultWithIndex.result + alphabet.indexOf(c) * pow(alphabet.base, resultWithIndex.index).toInt, 34 | resultWithIndex.index + 1 35 | ) 36 | } 37 | .result 38 | } 39 | } 40 | 41 | class Alphabet(private val values: String) { 42 | require(values.toSet.size == values.length) 43 | def base: Int = values.length 44 | 45 | def valueOf(i: Int): Char = values.charAt(i) 46 | 47 | def indexOf(i: Char): Int = values.indexOf(i) 48 | } 49 | 50 | object Alphabet { 51 | val Base23 = new Alphabet("ABCDEFGHJKLMNPQRSTUVXYZ") 52 | } 53 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/pretty/ExampleSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import com.softwaremill.id.IdGenerator 4 | import org.scalatest.flatspec.AnyFlatSpec 5 | import org.scalatest.matchers.should.Matchers 6 | 7 | class ExampleSpec extends AnyFlatSpec with Matchers { 8 | 9 | it should "present example of usage" in { 10 | // create instance of it 11 | val generator: StringIdGenerator = PrettyIdGenerator.singleNode 12 | 13 | // generate ids 14 | val stringId = generator.nextId() 15 | stringId shouldNot be(empty) 16 | stringId should fullyMatch regex """[A-Z]{4}-[0-9]{5}-[A-Z]{4}-[0-9]{5}""" 17 | 18 | // or it might be used just for encoding existing ids 19 | val prettifier = IdPrettifier.default 20 | val id = prettifier.prettify(100L) // id = AAAA-00000-AAAA-01007 21 | id should be("AAAA-00000-AAAA-01007") 22 | 23 | // get seed 24 | val origin = prettifier.toIdSeed(id) // 100L 25 | origin should be(Right(100L)) 26 | 27 | // use custom prettifier 28 | val customPrettifier = IdPrettifier.custom( 29 | encoder = new AlphabetCodec(new Alphabet("ABC")), 30 | partsSize = 4, 31 | delimiter = '_', 32 | leadingZeros = false 33 | ) 34 | val customId = customPrettifier.prettify(1234567L) // BCAACAB_5671 35 | 36 | // construct custom PrettyIdGenerator 37 | val idGenerator: IdGenerator = new IdGenerator { 38 | override def nextId(): Long = ??? 39 | override def idBaseAt(timestamp: Long): Long = ??? 40 | } 41 | val customGenerator = new PrettyIdGenerator(idGenerator, customPrettifier) 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /core/src/main/scala/com/softwaremill/id/pretty/Damm.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import scala.annotation.tailrec 4 | 5 | /** Implementation of Damm Check Digit alogrithm take from http://en.wikipedia.org/wiki/Damm_algorithm 6 | * https://en.wikibooks.org/wiki/Algorithm_Implementation/Checksums/Damm_Algorithm 7 | */ 8 | object Damm { 9 | 10 | private val matrix = Array( 11 | Array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), 12 | Array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), 13 | Array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), 14 | Array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), 15 | Array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), 16 | Array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1), 17 | Array(5, 8, 6, 9, 7, 2, 0, 1, 3, 4), 18 | Array(8, 9, 4, 5, 3, 6, 2, 0, 1, 7), 19 | Array(9, 4, 3, 8, 6, 1, 7, 2, 0, 5), 20 | Array(2, 5, 8, 1, 4, 3, 6, 7, 9, 0) 21 | ) 22 | 23 | /** Calculates the checksum from the provided string 24 | * @param str 25 | * a string, only the numerics will be calculated 26 | */ 27 | def encode(str: String): Int = { 28 | 29 | @tailrec 30 | def fn(interim: Int, idx: Int): Int = 31 | if (idx >= str.length) { 32 | interim 33 | } else { 34 | val c = str.charAt(idx) 35 | // only push numerics... 36 | fn(if (c.isDigit) matrix(interim)(c - 48) else interim, idx + 1) 37 | } 38 | 39 | fn(0, 0) 40 | } 41 | 42 | /** Decorates the string with the checksum 43 | */ 44 | def apply(str: String): String = str + encode(str).toString 45 | 46 | /** Unapply method returning the string without the checksum if it matches otherwise None 47 | */ 48 | def unapply(str: String): Option[String] = 49 | if (isValid(str)) Some(str.substring(0, str.length - 1)) else None 50 | 51 | /** Determines if the string contains a valid checksum 52 | */ 53 | def isValid(str: String): Boolean = encode(str) == 0 54 | 55 | } 56 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/pretty/IdPrettifierBenchmarkSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import com.fasterxml.uuid.{EthernetAddress, Generators} 4 | import com.softwaremill.id.DefaultIdGenerator 5 | import org.scalatest.flatspec.AnyFlatSpec 6 | import org.scalatest.matchers.should.Matchers 7 | 8 | class IdPrettifierBenchmarkSpec extends AnyFlatSpec with Matchers { 9 | behavior of "IdPrettifier" 10 | 11 | private def printResult(start: Long, stop: Long) = println(s"${(stop - start) / 1000.0} s") 12 | 13 | it should "measure performance of id prettifier" in { 14 | val idGenerator = new DefaultIdGenerator() 15 | val prettifier = IdPrettifier.default 16 | val times = 1 to 10000 17 | val start1 = System.currentTimeMillis() 18 | times.foreach { _ => 19 | prettifier.prettify(idGenerator.nextId()) 20 | } 21 | val stop1 = System.currentTimeMillis() 22 | val start2 = System.currentTimeMillis() 23 | val generator = Generators.timeBasedGenerator(EthernetAddress.fromInterface()) 24 | times.foreach { _ => 25 | generator.generate() 26 | } 27 | val stop2 = System.currentTimeMillis() 28 | println("Results for Prettifier:") 29 | printResult(start1, stop1) 30 | println("Results for UUID:") 31 | printResult(start2, stop2) 32 | } 33 | 34 | it should "measure performance of calculating seed ID" in { 35 | val idGenerator = new DefaultIdGenerator() 36 | val prettifier = IdPrettifier.default 37 | val times = 1 to 10000 38 | val seeds = times.map { _ => 39 | val seed = idGenerator.nextId() 40 | (seed, prettifier.prettify(seed)) 41 | } 42 | val start = System.currentTimeMillis() 43 | seeds.foreach { s => 44 | val value = prettifier.toIdSeed(s._2) 45 | value should be(Right(s._1)) 46 | } 47 | val stop = System.currentTimeMillis() 48 | println("Results for calculating seed:") 49 | printResult(start, stop) 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Id generator 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.softwaremill.common/id-generator_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.softwaremill.common/id-generator_2.12) 4 | 5 | Generate unique ids. A default generator is provided, based on [Twitter Snowflake](https://github.com/twitter/snowflake), 6 | which generates time-based ids. Besides that library provide `IdPrettifier` which may convert `Long` into user friendly id such `HPJD-72036-HAPK-58077`. `IdPrettifier` preserve Long's monotonicity, provides checksum and produce id with constant length (if it's not configured otherwise). It also maybe configured to user custom part sizes, separator or don't use leasing zeros to provide fixed length. More information you will find in the [blogpost](https://blog.softwaremill.com/new-pretty-id-generator-in-scala-commons-39b0fc6b6210) about it. 7 | 8 | SBT depedency: 9 | 10 | ````scala 11 | libraryDependencies += "com.softwaremill.common" %% "id-generator" % "1.4.0" 12 | ```` 13 | 14 | Examples 15 | ```scala 16 | //create instance of it 17 | val generator:StringIdGenerator = PrettyIdGenerator.singleNode 18 | 19 | //generate ids 20 | val stringId = generator.nextId() 21 | stringId shouldNot be(empty) 22 | stringId should fullyMatch regex """[A-Z]{4}-[0-9]{5}-[A-Z]{4}-[0-9]{5}""" 23 | 24 | //or it might be used just for encoding existing ids 25 | val prettifier = IdPrettifier.default 26 | val id = prettifier.prettify(100L) //id = AAAA-00000-AAAA-01007 27 | id should be("AAAA-00000-AAAA-01007") 28 | 29 | //get seed 30 | val origin = prettifier.toIdSeed(id) // 100L 31 | origin should be(Right(100L)) 32 | 33 | //use custom prettifier 34 | val customPrettifier = IdPrettifier.custom(encoder = new AlphabetCodec(new Alphabet("ABC")), partsSize = 4, delimiter = '_', leadingZeros = false) 35 | val customId = customPrettifier.prettify(1234567L) //BCAACAB_5671 36 | 37 | //construct custom PrettyIdGenerator 38 | val idGenerator:IdGenerator = new IdGenerator { 39 | override def nextId(): Long = ??? 40 | override def idBaseAt(timestamp: Long): Long = ??? 41 | } 42 | val customGenerator = new PrettyIdGenerator(idGenerator, customPrettifier) 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | branches: ['**'] 5 | push: 6 | branches: ['**'] 7 | tags: [v*] 8 | jobs: 9 | ci: 10 | # run on external PRs, but not on internal PRs since those will be run by push to branch 11 | if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository 12 | runs-on: ubuntu-20.04 13 | env: 14 | JAVA_OPTS: -Xmx4G 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v2 18 | - name: Set up JDK 11 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | - name: Cache sbt 23 | uses: actions/cache@v2 24 | with: 25 | path: | 26 | ~/.sbt 27 | ~/.ivy2/cache 28 | ~/.coursier 29 | key: sbt-cache-${{ runner.os }}-${{ hashFiles('project/build.properties') }} 30 | - name: Compile 31 | run: sbt -v compile 32 | - name: Test 33 | run: sbt -v test 34 | - name: Cleanup 35 | run: | 36 | rm -rf "$HOME/.ivy2/local" || true 37 | find $HOME/.ivy2/cache -name "ivydata-*.properties" -delete || true 38 | find $HOME/.ivy2/cache -name "*-LM-SNAPSHOT*" -delete || true 39 | find $HOME/.cache/coursier/v1 -name "ivydata-*.properties" -delete || true 40 | find $HOME/.sbt -name "*.lock" -delete || true -name "*.lock" -delete || true 41 | 42 | publish: 43 | name: Publish release 44 | needs: [ci] 45 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v')) 46 | runs-on: ubuntu-20.04 47 | env: 48 | JAVA_OPTS: -Xmx4G 49 | steps: 50 | - name: Checkout 51 | uses: actions/checkout@v2 52 | - name: Set up JDK 11 53 | uses: actions/setup-java@v1 54 | with: 55 | java-version: 11 56 | - name: Cache sbt 57 | uses: actions/cache@v2 58 | with: 59 | path: | 60 | ~/.sbt 61 | ~/.ivy2/cache 62 | ~/.coursier 63 | key: sbt-cache-${{ runner.os }}-${{ hashFiles('project/build.properties') }} 64 | - name: Compile 65 | run: sbt compile 66 | - name: Publish artifacts 67 | run: sbt ci-release 68 | env: 69 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 70 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 71 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 72 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 73 | - name: Extract version from commit message 74 | run: | 75 | version=${GITHUB_REF/refs\/tags\/v/} 76 | echo "VERSION=$version" >> $GITHUB_ENV 77 | env: 78 | COMMIT_MSG: ${{ github.event.head_commit.message }} 79 | - name: Publish release notes 80 | uses: release-drafter/release-drafter@v5 81 | with: 82 | config-name: release-drafter.yml 83 | publish: true 84 | name: "v${{ env.VERSION }}" 85 | tag: "v${{ env.VERSION }}" 86 | version: "v${{ env.VERSION }}" 87 | env: 88 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 89 | - name: Cleanup 90 | run: | 91 | rm -rf "$HOME/.ivy2/local" || true 92 | find $HOME/.ivy2/cache -name "ivydata-*.properties" -delete || true 93 | find $HOME/.ivy2/cache -name "*-LM-SNAPSHOT*" -delete || true 94 | find $HOME/.cache/coursier/v1 -name "ivydata-*.properties" -delete || true 95 | find $HOME/.sbt -name "*.lock" -delete || true 96 | -------------------------------------------------------------------------------- /core/src/main/scala/com/softwaremill/id/IdGenerator.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id 2 | 3 | import com.typesafe.scalalogging.StrictLogging 4 | 5 | /** Generates *unique* identifiers. There are *no* other requirements (e.g. randomness) as to the returned values. 6 | */ 7 | trait IdGenerator { 8 | def nextId(): Long 9 | 10 | /** An id base at the given timestamp. Should be smaller than all ids generated at that time, and bigger than all ids 11 | * generated before that time. 12 | */ 13 | def idBaseAt(timestamp: Long): Long 14 | } 15 | 16 | /** Generates time-based unique ids. Each node should have a different `workerId`. 17 | * 18 | * *Synchronizes* to assure thread-safety! 19 | */ 20 | class DefaultIdGenerator(workerId: Long = 1, datacenterId: Long = 1, epoch: Long = 1288834974657L) extends IdGenerator { 21 | private val idWorker = new IdWorker(workerId = workerId, datacenterId = datacenterId, epoch = epoch) 22 | 23 | def nextId(): Long = { 24 | synchronized { 25 | idWorker.nextId() 26 | } 27 | } 28 | 29 | def idBaseAt(timestamp: Long): Long = { 30 | idWorker.idForTimestamp(timestamp) 31 | } 32 | } 33 | 34 | /** An object that generates IDs. This is broken into a separate class in case we ever want to support multiple worker 35 | * threads per process 36 | * 37 | * Copied from: https://github.com/twitter/snowflake/tree/master/src/main/scala/com/twitter/service/snowflake Modified 38 | * to fit our logging, removed stats. 39 | * 40 | * Single threaded! 41 | */ 42 | private[id] class IdWorker( 43 | workerId: Long, 44 | datacenterId: Long, 45 | var sequence: Long = 0L, 46 | val epoch: Long = 1288834974657L 47 | ) extends StrictLogging { 48 | 49 | private val workerIdBits = 5L 50 | private val datacenterIdBits = 5L 51 | private val maxWorkerId = -1L ^ (-1L << workerIdBits) 52 | private val maxDatacenterId = -1L ^ (-1L << datacenterIdBits) 53 | private val sequenceBits = 12L 54 | 55 | private val workerIdShift = sequenceBits 56 | private val datacenterIdShift = sequenceBits + workerIdBits 57 | private val timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits 58 | private val sequenceMask = -1L ^ (-1L << sequenceBits) 59 | 60 | private var lastTimestamp = -1L 61 | 62 | // sanity check for workerId 63 | if (workerId > maxWorkerId || workerId < 0) { 64 | throw new IllegalArgumentException("worker Id can't be greater than %d or less than 0".format(maxWorkerId)) 65 | } 66 | 67 | if (datacenterId > maxDatacenterId || datacenterId < 0) { 68 | throw new IllegalArgumentException("datacenter Id can't be greater than %d or less than 0".format(maxDatacenterId)) 69 | } 70 | 71 | logger.info( 72 | "Id worker starting. Timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d" 73 | .format( 74 | timestampLeftShift, 75 | datacenterIdBits, 76 | workerIdBits, 77 | sequenceBits, 78 | workerId 79 | ) 80 | ) 81 | 82 | def get_worker_id(): Long = workerId 83 | def get_datacenter_id(): Long = datacenterId 84 | def get_timestamp() = System.currentTimeMillis 85 | 86 | def nextId(): Long = { 87 | var timestamp = timeGen() 88 | if (lastTimestamp == timestamp) { 89 | sequence = (sequence + 1) & sequenceMask 90 | if (sequence == 0) { 91 | timestamp = tilNextMillis(lastTimestamp) 92 | } 93 | } else { 94 | sequence = 0 95 | } 96 | 97 | if (timestamp < lastTimestamp) { 98 | logger.error("Clock is moving backwards. Rejecting requests until %d.".format(lastTimestamp)) 99 | throw new RuntimeException( 100 | "Invalid system clock: Clock moved backwards. Refusing to generate id for %d milliseconds".format( 101 | lastTimestamp - timestamp 102 | ) 103 | ) 104 | } 105 | 106 | lastTimestamp = timestamp 107 | ((timestamp - epoch) << timestampLeftShift) | 108 | (datacenterId << datacenterIdShift) | 109 | (workerId << workerIdShift) | 110 | sequence 111 | } 112 | 113 | def idForTimestamp(timestamp: Long): Long = (timestamp - epoch) << timestampLeftShift 114 | 115 | protected def tilNextMillis(lastTimestamp: Long): Long = { 116 | var timestamp = timeGen() 117 | while (timestamp <= lastTimestamp) { 118 | timestamp = timeGen() 119 | } 120 | timestamp 121 | } 122 | 123 | protected def timeGen(): Long = System.currentTimeMillis() 124 | } 125 | -------------------------------------------------------------------------------- /core/src/main/scala/com/softwaremill/id/pretty/IdPrettyfier.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import com.softwaremill.id.{DefaultIdGenerator, IdGenerator} 4 | 5 | /** It makes Long ids more readable and user friendly, it also adds checksum. 6 | * 7 | * @param encoder 8 | * it the result needs to be monotonic, use monotonic Coded e.g. AlphabetCoded with alphabet where char values are 9 | * monotonic 10 | * @param partsSize 11 | * the long is chopped on the parts, here you specify the part length (only even parts are encoded with codec) 12 | * @param delimiter 13 | * sign between parts 14 | * @param leadingZeros 15 | * prettifier will make id with constant length 16 | */ 17 | class IdPrettifier private ( 18 | encoder: Codec, 19 | partsSize: Int, 20 | delimiter: Char, 21 | leadingZeros: Boolean 22 | ) { 23 | 24 | val zeroChar = encoder.encode(0).charAt(0) 25 | val maxEncodedLength = encoder.encode(scala.math.pow(10, partsSize).toLong - 1).length 26 | 27 | def prettify(idSeed: Long): String = { 28 | require(idSeed >= 0) 29 | val parts = divide(Damm(idSeed.toString)) 30 | val partsToConvert = withLeadingZeros(parts) { ps => 31 | addLeadingZerosParts(ps) 32 | } 33 | convertParts(partsToConvert) 34 | } 35 | 36 | def isValid(id: String): Boolean = Damm.isValid(decodeSeedWithCheckDigit(id)) 37 | 38 | def toIdSeed(id: String): Either[ConversionError, Long] = convertToLong(id) 39 | 40 | private def divide(s: String): Seq[String] = 41 | s.reverse.grouped(partsSize).toSeq.reverse.map(_.reverse) 42 | 43 | private def addLeadingZerosParts(parts: Seq[String]): Seq[String] = { 44 | val maxParts = scala.math.ceil(20d / partsSize.toDouble).toInt 45 | parts.reverse.padTo(maxParts, "0").reverse 46 | } 47 | 48 | case class ConversionError(invalidId: String) 49 | 50 | private def convertToLong(s: String): Either[ConversionError, Long] = { 51 | val decodedWithCheckDigit: String = decodeSeedWithCheckDigit(s) 52 | if (Damm.isValid(decodedWithCheckDigit)) { 53 | try { 54 | Right(decodedWithCheckDigit.dropRight(1).toLong) 55 | } catch { 56 | case e: NumberFormatException => 57 | Left(ConversionError(s)) 58 | } 59 | } else { 60 | Left(ConversionError(s)) 61 | } 62 | } 63 | 64 | private def withLeadingZeros[T](t: T)(forLeadingZeros: (T => T)): T = 65 | if (leadingZeros) forLeadingZeros(t) else t 66 | 67 | private def convertParts(parts: Seq[String]): String = 68 | parts 69 | .foldRight(Seq[String]()) { (part, result) => 70 | val isEven = result.length % 2 == 0 71 | if (isEven) { 72 | val convertedPart = withLeadingZeros(part) { p => 73 | addLeadingZeros(p, '0', partsSize) 74 | } 75 | Seq(convertedPart) ++ result 76 | } else { 77 | val encoded = encoder.encode(part.toInt) 78 | val convertedPart = withLeadingZeros(encoded) { e => 79 | addLeadingZeros(e, zeroChar, maxEncodedLength) 80 | } 81 | Seq(convertedPart) ++ result 82 | } 83 | } 84 | .mkString(delimiter.toString) 85 | 86 | private def addLeadingZeros(encodedPart: String, zeroChar: Char, maxPartSize: Int): String = 87 | encodedPart.reverse.padTo(maxPartSize, zeroChar).reverse 88 | 89 | private def decodeSeedWithCheckDigit(s: String) = { 90 | val parts = s.split(delimiter) 91 | val decodedWithCheckDigit = parts 92 | .foldRight(Seq[String]()) { (part, result) => 93 | val isEven = result.length % 2 == 0 94 | if (isEven) { 95 | Seq(part) ++ result 96 | } else { 97 | val decoded = addLeadingZeros(encoder.decode(part).toString, '0', partsSize) 98 | Seq(decoded.toString) ++ result 99 | } 100 | } 101 | .mkString 102 | decodedWithCheckDigit 103 | } 104 | } 105 | 106 | object IdPrettifier { 107 | val default = new IdPrettifier(new AlphabetCodec(Alphabet.Base23), 5, '-', true) 108 | def custom( 109 | encoder: Codec = new AlphabetCodec(Alphabet.Base23), 110 | partsSize: Int = 5, 111 | delimiter: Char = '-', 112 | leadingZeros: Boolean = true 113 | ) = new IdPrettifier(encoder, partsSize, delimiter, leadingZeros) 114 | } 115 | 116 | object PrettyIdGenerator { 117 | val singleNode = new PrettyIdGenerator(new DefaultIdGenerator(), IdPrettifier.default) 118 | def distributed(workerId: Long, datacenterId: Long) = 119 | new PrettyIdGenerator(new DefaultIdGenerator(workerId, datacenterId), IdPrettifier.default) 120 | } 121 | 122 | class PrettyIdGenerator(idGenerator: IdGenerator, idPrettifier: IdPrettifier) extends StringIdGenerator { 123 | 124 | import idPrettifier._ 125 | 126 | def nextId(): String = prettify(idGenerator.nextId()) 127 | 128 | def idBaseAt(timestamp: Long): String = prettify(idGenerator.idBaseAt(timestamp)) 129 | } 130 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/pretty/IdPrettifierSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id.pretty 2 | 3 | import com.softwaremill.id.DefaultIdGenerator 4 | import org.scalatest.flatspec.AnyFlatSpec 5 | import org.scalatest.matchers.should.Matchers 6 | 7 | class IdPrettifierSpec extends AnyFlatSpec with Matchers { 8 | behavior of "IdPrettifier" 9 | 10 | val max = Long.MaxValue 11 | val exampleId = 824227036833910784L 12 | 13 | it should "generate pretty IDs with leading zeros" in { 14 | val default = IdPrettifier.default 15 | val maxPrettyId = default.prettify(max) 16 | val examplePrettyId = default.prettify(exampleId) 17 | 18 | maxPrettyId should be("HPJD-72036-HAPK-58077") 19 | examplePrettyId should be("ARPJ-27036-GVQS-07849") 20 | default.prettify(1) should be("AAAA-00000-AAAA-00013") 21 | 22 | val prettifierBy8 = IdPrettifier.custom(partsSize = 8) 23 | prettifierBy8.prettify(1) should be("00000000-AAAAAA-00000013") 24 | prettifierBy8.prettify(max) should be("00009223-FTYTHN-47758077") 25 | } 26 | 27 | it should "generate pretty IDs without leading zeros" in { 28 | val prettifier = IdPrettifier.custom(leadingZeros = false) 29 | val maxPrettyId = prettifier.prettify(max) 30 | val examplePrettyId = prettifier.prettify(exampleId) 31 | 32 | maxPrettyId should be("HPJD-72036-HAPK-58077") 33 | examplePrettyId should be("RPJ-27036-GVQS-07849") 34 | prettifier.prettify(1) should be("13") 35 | 36 | val prettifierBy8 = IdPrettifier.custom(partsSize = 8, leadingZeros = false) 37 | prettifierBy8.prettify(1) should be("13") 38 | prettifierBy8.prettify(max) should be("9223-FTYTHN-47758077") 39 | 40 | } 41 | 42 | it should "find seed of pretty ID with leading zeros" in { 43 | val prettifiedWithLeading = IdPrettifier.default 44 | val maxPrettyId = prettifiedWithLeading.prettify(max) 45 | val examplePrettyId = prettifiedWithLeading.prettify(exampleId) 46 | 47 | prettifiedWithLeading.toIdSeed("HPJD-72036-HAPK-58077") should be(Right(max)) 48 | prettifiedWithLeading.toIdSeed("ARPJ-27036-GVQS-07849") should be(Right(exampleId)) 49 | prettifiedWithLeading.toIdSeed("AAAA-00000-AAAA-00013") should be(Right(1L)) 50 | } 51 | 52 | it should "find seed of pretty ID without leading zeros" in { 53 | val prettifiedWithoutTrailingZeros = IdPrettifier.custom(leadingZeros = false) 54 | val maxPrettyId = prettifiedWithoutTrailingZeros.prettify(max) 55 | val examplePrettyId = prettifiedWithoutTrailingZeros.prettify(exampleId) 56 | 57 | prettifiedWithoutTrailingZeros.toIdSeed("HPJD-72036-HAPK-58077") should be(Right(max)) 58 | prettifiedWithoutTrailingZeros.toIdSeed("RPJ-27036-GVQS-07849") should be(Right(exampleId)) 59 | prettifiedWithoutTrailingZeros.toIdSeed("13") should be(Right(1L)) 60 | } 61 | 62 | it should "validate pretty IDs" in { 63 | import IdPrettifier.default._ 64 | isValid("HPJD-72036-HAPK-58077") should be(true) 65 | isValid("HPJD-72036-HAPK-58077") should be(true) 66 | isValid("ARPJ-27036-GVQS-07849") should be(true) 67 | isValid("ARPJ-27036-GVQS-07840") should be(false) 68 | isValid("ARPJ-27036-GVQS-07489") should be(false) 69 | isValid("ARPJ-27036-GVQZ-07489") should be(false) 70 | } 71 | 72 | it should "preserve ID monotonicity" in { 73 | import IdPrettifier.default._ 74 | val idGenerator = new DefaultIdGenerator() 75 | val ids = (1 to 100).map(_ => prettify(idGenerator.nextId())) 76 | ids.sorted should be(ids) 77 | ids.sorted.reverse should be(ids.reverse) 78 | } 79 | 80 | it should "keep same id length" in { 81 | import IdPrettifier.default._ 82 | val minId: String = prettify(0) 83 | val maxId: String = prettify(max) 84 | 85 | minId should have length maxId.length 86 | } 87 | 88 | it should "calculate seed properly - with default settings" in { 89 | val idGenerator = new DefaultIdGenerator() 90 | val prettifier = IdPrettifier.default 91 | 92 | val times = 1 to 10000 93 | times.map { _ => 94 | val seed = idGenerator.nextId() 95 | val id = prettifier.prettify(seed) 96 | prettifier.toIdSeed(id) should be(Right(seed)) 97 | } 98 | } 99 | 100 | it should "calculate seed properly - without leading zeros" in { 101 | val idGenerator = new DefaultIdGenerator() 102 | val prettifier = IdPrettifier.custom(leadingZeros = false) 103 | 104 | val times = 1 to 10000 105 | times.map { _ => 106 | val seed = idGenerator.nextId() 107 | val id = prettifier.prettify(seed) 108 | val decodedSeed = prettifier.toIdSeed(id) 109 | decodedSeed should be(Right(seed)) 110 | } 111 | 112 | times.map(_ => randomLong()).map { seed => 113 | val id = prettifier.prettify(seed) 114 | val decodedSeed = prettifier.toIdSeed(id) 115 | decodedSeed should be(Right(seed)) 116 | } 117 | } 118 | 119 | it should "calculate seed properly - without leading zeros and short alphabet" in { 120 | val idGenerator = new DefaultIdGenerator() 121 | val prettifier = IdPrettifier.custom(encoder = new AlphabetCodec(new Alphabet("ABC")), partsSize = 2) 122 | 123 | val times = 1 to 10000 124 | times.map { _ => 125 | val seed = idGenerator.nextId() 126 | val id = prettifier.prettify(seed) 127 | val decodedSeed = prettifier.toIdSeed(id) 128 | decodedSeed should be(Right(seed)) 129 | } 130 | 131 | times.map(_ => randomLong()).map { seed => 132 | val id = prettifier.prettify(seed) 133 | val decodedSeed = prettifier.toIdSeed(id) 134 | decodedSeed should be(Right(seed)) 135 | } 136 | } 137 | 138 | private def randomLong(): Long = { 139 | (Math.random() * Math.pow(10, 17)).toLong 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /core/src/test/scala/com/softwaremill/id/DefaultIdGeneratorSpec.scala: -------------------------------------------------------------------------------- 1 | package com.softwaremill.id 2 | 3 | import org.scalatest.flatspec.AnyFlatSpec 4 | import org.scalatest.matchers.should.Matchers 5 | 6 | class DefaultIdGeneratorSpec extends AnyFlatSpec with Matchers { 7 | val workerMask = 0x000000000001f000L 8 | val datacenterMask = 0x00000000003e0000L 9 | val timestampMask = 0xffffffffffc00000L 10 | 11 | class EasyTimeWorker(workerId: Long, datacenterId: Long, timeStart: Long = System.currentTimeMillis()) 12 | extends IdWorker(workerId, datacenterId) { 13 | var timeMaker = () => timeStart 14 | override def timeGen(): Long = { 15 | timeMaker() 16 | } 17 | } 18 | 19 | class WakingIdWorker(workerId: Long, datacenterId: Long) extends EasyTimeWorker(workerId, datacenterId) { 20 | var slept = 0 21 | override def tilNextMillis(lastTimestamp: Long): Long = { 22 | slept += 1 23 | super.tilNextMillis(lastTimestamp) 24 | } 25 | } 26 | 27 | behavior of "IdWorker" 28 | 29 | it should "generate an id" in { 30 | val s = new IdWorker(1, 1) 31 | val id: Long = s.nextId() 32 | id should be > 0L 33 | } 34 | 35 | it should "return an accurate timestamp" in { 36 | val s = new IdWorker(1, 1) 37 | val t = System.currentTimeMillis 38 | (s.get_timestamp() - t) should be < 50L 39 | } 40 | 41 | it should "return the correct job id" in { 42 | val s = new IdWorker(1, 1) 43 | s.get_worker_id() should be(1L) 44 | } 45 | 46 | it should "return the correct dc id" in { 47 | val s = new IdWorker(1, 1) 48 | s.get_datacenter_id() should be(1L) 49 | } 50 | 51 | it should "properly mask worker id" in { 52 | val workerId = 0x1f 53 | val datacenterId = 0 54 | val worker = new IdWorker(workerId, datacenterId) 55 | for (i <- 1 to 1000) { 56 | val id = worker.nextId() 57 | ((id & workerMask) >> 12) should be(workerId) 58 | } 59 | } 60 | 61 | it should "properly mask dc id" in { 62 | val workerId = 0 63 | val datacenterId = 0x1f 64 | val worker = new IdWorker(workerId, datacenterId) 65 | val id = worker.nextId() 66 | ((id & datacenterMask) >> 17) should be(datacenterId) 67 | } 68 | 69 | it should "properly mask timestamp" in { 70 | val worker = new EasyTimeWorker(31, 31) 71 | for (i <- 1 to 100) { 72 | val t = System.currentTimeMillis 73 | worker.timeMaker = () => t 74 | val id = worker.nextId() 75 | ((id & timestampMask) >> 22) should be(t - worker.epoch) 76 | } 77 | } 78 | 79 | it should "roll over sequence id" in { 80 | // put a zero in the low bit so we can detect overflow from the sequence 81 | val workerId = 4 82 | val datacenterId = 4 83 | val worker = new IdWorker(workerId, datacenterId) 84 | val startSequence = 0xffffff - 20 85 | val endSequence = 0xffffff + 20 86 | worker.sequence = startSequence 87 | 88 | for (i <- startSequence to endSequence) { 89 | val id = worker.nextId() 90 | ((id & workerMask) >> 12) should be(workerId) 91 | } 92 | } 93 | 94 | it should "generate increasing ids" in { 95 | val worker = new IdWorker(1, 1) 96 | var lastId = 0L 97 | for (i <- 1 to 100) { 98 | val id = worker.nextId() 99 | id should be > lastId 100 | lastId = id 101 | } 102 | } 103 | 104 | it should "generate 1 million ids quickly" in { 105 | val worker = new IdWorker(31, 31) 106 | val t = System.currentTimeMillis 107 | for (i <- 1 to 1000000) { 108 | var id = worker.nextId() 109 | id 110 | } 111 | val t2 = System.currentTimeMillis 112 | println("generated 1000000 ids in %d ms, or %,.0f ids/second".format(t2 - t, 1000000000.0 / (t2 - t))) 113 | 1 should be > 0 114 | } 115 | 116 | it should "sleep if we would rollover twice in the same millisecond" in { 117 | var queue = new scala.collection.mutable.Queue[Long]() 118 | val worker = new WakingIdWorker(1, 1) 119 | val iter = List(2L, 2L, 3L).iterator 120 | worker.timeMaker = () => iter.next 121 | worker.sequence = 4095 122 | worker.nextId() 123 | worker.sequence = 4095 124 | worker.nextId() 125 | worker.slept should be(1) 126 | } 127 | 128 | it should "generate only unique ids" in { 129 | val worker = new IdWorker(31, 31) 130 | var set = new scala.collection.mutable.HashSet[Long]() 131 | val n = 2000000 132 | (1 to n).foreach { i => 133 | val id = worker.nextId() 134 | if (set.contains(id)) { 135 | println(java.lang.Long.toString(id, 2)) 136 | } else { 137 | set += id 138 | } 139 | } 140 | set.size should be(n) 141 | } 142 | 143 | it should "generate ids over 50 billion" in { 144 | val worker = new IdWorker(0, 0) 145 | worker.nextId() should be > 50000000000L 146 | } 147 | 148 | it should "generate ids older then lower bound" in { 149 | // given 150 | val worker = new IdWorker(0, 0) 151 | val lowerBound = worker.idForTimestamp(System.currentTimeMillis()) 152 | 153 | // when 154 | val ids = List(worker.nextId(), worker.nextId(), worker.nextId()) 155 | 156 | // then 157 | ids.foreach(_ >= lowerBound should be(true)) 158 | } 159 | 160 | it should "generate older lowerBound then next generated ids from distinct workers" in { 161 | // given 162 | val worker = new IdWorker(0, 0) 163 | val lowerBound = worker.idForTimestamp(System.currentTimeMillis()) 164 | 165 | // when 166 | val ids = List( 167 | new DefaultIdGenerator(workerId = 1).nextId(), 168 | new DefaultIdGenerator(workerId = 2).nextId(), 169 | new DefaultIdGenerator(workerId = 3).nextId() 170 | ) 171 | 172 | // then 173 | ids.foreach(_ >= lowerBound should be(true)) 174 | } 175 | 176 | it should "generate range of ids that catches only 3 oldest ids" in { 177 | // given 178 | val currentPoint = System.currentTimeMillis() 179 | val upperBoundOverheadAndExtraTime = 300000 // (datacenterId << datacenterIdShift) | (workerId << workerIdShift) 180 | 181 | val gen = new EasyTimeWorker(0, 1, timeStart = currentPoint) 182 | val lowerBound = gen.idForTimestamp(currentPoint) 183 | val upperBound = lowerBound + upperBoundOverheadAndExtraTime 184 | 185 | val ids = List(gen.nextId(), gen.nextId(), gen.nextId()) 186 | 187 | // when 188 | val laterMilis = 120 189 | val olderIds = new EasyTimeWorker(1, 2, timeStart = currentPoint + laterMilis) 190 | val newList = ids ++ List(olderIds.nextId(), olderIds.nextId(), olderIds.nextId()) 191 | 192 | // then 193 | newList.count(id => id >= lowerBound && id < upperBound) should be(3) 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 SoftwareMill 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------