org.apache.commons.lang3.RandomStringUtils Scala Examples

The following examples show how to use org.apache.commons.lang3.RandomStringUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: NotebookDaoImplIntegSpec.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.workflowmanager.storage.impl

import scala.concurrent.{Await, Future}

import org.apache.commons.lang3.RandomStringUtils
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, Matchers}

import ai.deepsense.commons.StandardSpec
import ai.deepsense.commons.utils.Logging
import ai.deepsense.graph.Node
import ai.deepsense.models.workflows.Workflow
import ai.deepsense.workflowmanager.storage.GraphJsonTestSupport

class NotebookDaoImplIntegSpec
  extends StandardSpec
  with ScalaFutures
  with MockitoSugar
  with Matchers
  with BeforeAndAfter
  with GraphJsonTestSupport
  with SlickTestSupport
  with Logging {

  var notebooksDao: NotebookDaoImpl = _

  val n1@(notebook1Id, node1Id, notebook1) = createNotebook()
  val n2@(notebook2Id, node2Id, notebook2) = createNotebook()
  val n3@(notebook3Id, node3Id, notebook3) = createNotebook()
  val n4 = (notebook1Id, node2Id, notebook2)

  val storedNotebooks = Set(n1, n2, n4)

  before {
    notebooksDao = new NotebookDaoImpl(db, driver)
  }

  "NotebooksDao" should {

    "find notebook by id" in withStoredNotebooks(storedNotebooks) {
      whenReady(notebooksDao.get(notebook1Id, node1Id)) { notebook =>
        notebook shouldBe Some(notebook1)
      }
    }

    "get all notebooks for workflow" in withStoredNotebooks(storedNotebooks) {
      whenReady(notebooksDao.getAll(notebook1Id)) { notebooks =>
        notebooks.size shouldBe 2
        notebooks.get(node1Id) shouldBe Some(notebook1)
        notebooks.get(node2Id) shouldBe Some(notebook2)
      }
    }

    "return None if notebook does not exist" in withStoredNotebooks(storedNotebooks) {
      whenReady(notebooksDao.get(notebook3Id, node3Id)) { notebook =>
        notebook shouldBe None
      }
    }

    "create notebook" in withStoredNotebooks(storedNotebooks) {
      whenReady(notebooksDao.save(notebook3Id, node3Id, notebook3)) { _ =>
        whenReady(notebooksDao.get(notebook3Id, node3Id)) { notebook =>
          notebook shouldBe Some(notebook3)
        }
      }
    }

    "update notebook" in withStoredNotebooks(storedNotebooks) {
      val modifiedNotebook2 = "modified"
      whenReady(notebooksDao.save(notebook2Id, node2Id, modifiedNotebook2)) { _ =>
        whenReady(notebooksDao.get(notebook2Id, node2Id)) { notebook =>
          notebook shouldBe Some(modifiedNotebook2)
        }
      }
    }
  }

  private def withStoredNotebooks(
      storedNotebooks: Set[(Workflow.Id, Node.Id, String)])(testCode: => Any): Unit = {

    Await.ready(notebooksDao.create(), operationDuration)

    val s = Future.sequence(storedNotebooks.map {
      case (workflowId, nodeId, notebook) => notebooksDao.save(workflowId, nodeId, notebook)
    })
    Await.ready(s, operationDuration)

    try {
      testCode
    } finally {
      Await.ready(notebooksDao.drop(), operationDuration)
    }
  }

  def createNotebook(): (Workflow.Id, Node.Id, String) = {
    (Workflow.Id.randomId, Node.Id.randomId, RandomStringUtils.randomAlphanumeric(16))
  }
} 
Example 2
Source File: User.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.domain.membership

import java.util.UUID

import org.apache.commons.lang3.RandomStringUtils
import org.joda.time.DateTime
import vinyldns.core.crypto.CryptoAlgebra
import vinyldns.core.domain.membership.LockStatus.LockStatus

object LockStatus extends Enumeration {
  type LockStatus = Value
  val Locked, Unlocked = Value
}

final case class User(
    userName: String,
    accessKey: String,
    secretKey: String,
    firstName: Option[String] = None,
    lastName: Option[String] = None,
    email: Option[String] = None,
    created: DateTime = DateTime.now,
    id: String = UUID.randomUUID().toString,
    isSuper: Boolean = false,
    lockStatus: LockStatus = LockStatus.Unlocked,
    isSupport: Boolean = false,
    isTest: Boolean = false
) {

  def updateUserLockStatus(lockStatus: LockStatus): User =
    this.copy(lockStatus = lockStatus)

  def regenerateCredentials(): User =
    copy(accessKey = User.generateKey, secretKey = User.generateKey)

  def withEncryptedSecretKey(cryptoAlgebra: CryptoAlgebra): User =
    copy(secretKey = cryptoAlgebra.encrypt(secretKey))
}

object User {
  def generateKey: String = RandomStringUtils.randomAlphanumeric(20)
} 
Example 3
Source File: DocumentIdFactory.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.document

import collection.JavaConversions._
import org.apache.commons.lang3.RandomStringUtils
import play.api.Logger
import scala.concurrent.Await
import scala.concurrent.duration._
import services.generated.Tables._
import storage.db.DB

object DocumentIdFactory {
  
  // We use random alphanumeric IDs with 14 chars length (because 62^14 should be enough for anyone (TM))  
  val ID_LENGTH = 14
  
  // Utility function to check if an ID exists in the DB
  def existsId(id: String)(implicit db: DB) = {
    def checkExists() = db.query { sql =>
      val count = sql.select(DOCUMENT.ID)
         .from(DOCUMENT)
         .where(DOCUMENT.ID.equal(id))
         .fetchArray()
         .length
      
      count > 0
    }
    
    Await.result(checkExists(), 10.seconds)    
  }
  
  def generateRandomID(retriesLeft: Int = 10)(implicit db: DB): String = {
    
    // Takes a set of strings and returns those that already exist in the DB as doc IDs
    def findIds(ids: Set[String])(implicit db: DB) = db.query { sql =>
      sql.select(DOCUMENT.ID)
         .from(DOCUMENT)
         .where(DOCUMENT.ID.in(ids))
         .fetchArray()
         .map(_.value1).toSet    
    }
    
    // Generate 10 random IDs
    val randomIds = 
      (1 to 10).map(_ => RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase).toSet

    // Match them all against the database and remove those that already exist
    val idsAlreadyInDB = Await.result(findIds(randomIds), 10.seconds)    
    val uniqueIds = randomIds.filter(id => !idsAlreadyInDB.contains(id))
    
    if (uniqueIds.size > 0) {
      uniqueIds.head
    } else if (retriesLeft > 0) {
      Logger.warn("Failed to generate unique random document ID")
      generateRandomID(retriesLeft - 1)
    } else {
      throw new RuntimeException("Failed to create unique document ID")
    }
  }
  
} 
Example 4
Source File: Token.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data

import org.apache.commons.lang3.RandomStringUtils
import org.joda.time.format.ISODateTimeFormat.{dateTime, dateTimeParser}
import org.joda.time.{DateTime, DateTimeZone}
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class Token(id: Option[String], description: String, value: String, created: DateTime)

object Token {
  final val KeyId = "id"
  final val KeyDescription = "description"
  final val KeyValue = "value"
  final val KeyCreated = "created"

  final val DefaultName = "default"

  implicit val datetimeReads: Reads[DateTime] =  __.read[String].map(dateTimeParser.parseDateTime)
  implicit val datetimeWrites = new Writes[DateTime] {
    def writes(value: DateTime) = JsString(dateTime.print(value))
  }


  implicit val tokenReads: Reads[Token] = (
      (__ \ KeyId).readNullable[String] and
      (__ \ KeyDescription).read[String] and
      (__ \ KeyValue).read[String] and
      (__ \ KeyCreated).read[DateTime]
    )(Token.apply _)

  implicit val tokenWrites: Writes[Token] = (
      (__ \ KeyId).writeNullable[String] and
      (__ \ KeyDescription).write[String] and
      (__ \ KeyValue).write[String] and
      (__ \ KeyCreated).write[DateTime]
    )(unlift(Token.unapply))

  val secureRandom = new java.security.SecureRandom

  def createToken(description: String): Token =
    new Token(None, description,
      RandomStringUtils.random(56, 0, 0, true, true, null, secureRandom),
      new DateTime().withZone(DateTimeZone.UTC)
    )
}