alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (LeveldbIdMapping.scala)

This example Akka source code file (LeveldbIdMapping.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, akka, dbiterator, int, leveldbidmapping, leveldbstore, map, none, some, string, utf-8

The LeveldbIdMapping.scala Akka example source code

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */

package akka.persistence.journal.leveldb

import org.iq80.leveldb.DBIterator

import akka.actor.Actor

/**
 * INTERNAL API.
 *
 * LevelDB backed persistent mapping of `String`-based persistent actor and channel ids to numeric ids.
 */
private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore ⇒
  import Key._

  private val idOffset = 10
  private var idMap: Map[String, Int] = Map.empty

  /**
   * Get the mapped numeric id for the specified persistent actor or channel `id`. Creates and
   * stores a new mapping if necessary.
   */
  def numericId(id: String): Int = idMap.get(id) match {
    case None    ⇒ writeIdMapping(id, idMap.size + idOffset)
    case Some(v) ⇒ v
  }

  private def readIdMap(): Map[String, Int] = withIterator { iter ⇒
    iter.seek(keyToBytes(idKey(idOffset)))
    readIdMap(Map.empty, iter)
  }

  private def readIdMap(pathMap: Map[String, Int], iter: DBIterator): Map[String, Int] = {
    if (!iter.hasNext) pathMap else {
      val nextEntry = iter.next()
      val nextKey = keyFromBytes(nextEntry.getKey)
      if (!isIdKey(nextKey)) pathMap else {
        val nextVal = new String(nextEntry.getValue, "UTF-8")
        readIdMap(pathMap + (nextVal -> id(nextKey)), iter)
      }
    }
  }

  private def writeIdMapping(id: String, numericId: Int): Int = {
    idMap = idMap + (id -> numericId)
    leveldb.put(keyToBytes(idKey(numericId)), id.getBytes("UTF-8"))
    numericId
  }

  override def preStart() {
    idMap = readIdMap()
    super.preStart()
  }
}

Other Akka source code examples

Here is a short list of links related to this Akka LeveldbIdMapping.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.