code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
/* * Copyright 2013-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package laika.tree import org.scalatest.FlatSpec import org.scalatest.Matchers import laika.api.Parse import laika.parse.markdown.Markdown import laika.rewrite.DocumentCursor import laika.rewrite.RewriteRules import laika.tree.Elements._ import laika.tree.helper.ModelBuilder class DocumentAPISpec extends FlatSpec with Matchers with ModelBuilder { "The Document API" should "allow to specify a title in a config section" in { val markup = """{% title: Foo and Bar %} | |# Ignored Title | |Some text | |## Section | |Some more text""".stripMargin (Parse as Markdown fromString markup).title should be (List(txt("Foo and Bar"))) } it should "use the title from the first headline if it is not overridden in a config section" in { val markup = """# Title | |Some text | |## Section | |Some more text""".stripMargin (Parse as Markdown fromString markup).title should be (List(txt("Title"))) } it should "return an empty list if there is neither a structure with a title nor a title in a config section" in { val markup = """# Section 1 | |Some text | |# Section 2 | |Some more text""".stripMargin (Parse as Markdown fromString markup).title should be (Nil) } it should "produce the same result when rewriting a document once or twice" in { val markup = """# Section 1 | |Some text | |# Section 2 | |Some more text""".stripMargin val doc = (Parse as Markdown withoutRewrite) fromString markup val rewritten1 = doc.rewrite(RewriteRules.defaults(DocumentCursor(doc))) val rewritten2 = rewritten1.rewrite(RewriteRules.defaults(DocumentCursor(rewritten1))) rewritten1.content should be (rewritten2.content) } it should "allow to rewrite the document using a custom rule" in { val markup = """# Section 1 | |Some text | |# Section 2 | |Some more text""".stripMargin val raw = (Parse as Markdown withoutRewrite) fromString markup val cursor = DocumentCursor(raw) val testRule: RewriteRule = { case Text("Some text",_) => Some(Text("Swapped")) } val rules = RewriteRules.chain(Seq(testRule, RewriteRules.defaults(cursor))) val rewritten = raw rewrite rules rewritten.content should be (root( Section(Header(1, List(Text("Section 1")), Id("section-1") + Styles("section")), List(p("Swapped"))), Section(Header(1, List(Text("Section 2")), Id("section-2") + Styles("section")), List(p("Some more text"))) )) } }
amuramatsu/Laika
core/src/test/scala/laika/tree/DocumentAPISpec.scala
Scala
apache-2.0
3,329
package org.jetbrains.plugins.scala.lang.psi.api.statements import javax.swing.Icon import com.intellij.psi.tree.IElementType import org.jetbrains.plugins.scala.icons.Icons import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes.kVAR import org.jetbrains.plugins.scala.lang.psi.api.expr.ScBlock import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.ScExtendsBlock import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef._ /** * @author Alexander Podkhalyuzin */ trait ScVariable extends ScValueOrVariable { override protected def keywordElementType: IElementType = kVAR override protected def isSimilarMemberForNavigation(member: ScMember, isStrict: Boolean): Boolean = member match { case other: ScVariable => super.isSimilarMemberForNavigation(other, isStrict) case _ => false } override def getIcon(flags: Int): Icon = { var parent = getParent while (parent != null) { parent match { case _: ScExtendsBlock => return Icons.FIELD_VAR case _: ScBlock => return Icons.VAR case _ => parent = parent.getParent } } null } }
gtache/intellij-lsp
intellij-lsp-dotty/src/org/jetbrains/plugins/scala/lang/psi/api/statements/ScVariable.scala
Scala
apache-2.0
1,124
package com.twitter.util /** * The Try type represents a computation that may either result in an exception * or return a success value. It is analogous to the Either type but encodes * common idioms for handling exceptional cases (such as rescue/ensure which * is analogous to try/finally). */ object Try { case class PredicateDoesNotObtain() extends Exception() def apply[R](r: => R): Try[R] = { try { Return(r) } catch { case NonFatal(e) => Throw(e) } } /** * Collect the results from the given Trys into a new Try. The result will be a Throw if any of * the argument Trys are Throws. The first Throw in the Seq is the one which is surfaced. */ def collect[A](ts: Seq[Try[A]]): Try[Seq[A]] = { if (ts.isEmpty) Return(Seq.empty[A]) else Try { ts map { t => t() } } } } /** * This class represents a computation that can succeed or fail. It has two * concrete implementations, Return (for success) and Throw (for failure) */ sealed abstract class Try[+R] { /** * Returns true if the Try is a Throw, false otherwise. */ def isThrow: Boolean /** * Returns true if the Try is a Return, false otherwise. */ def isReturn: Boolean /** * Returns the value from this Return or the given argument if this is a Throw. */ def getOrElse[R2 >: R](default: => R2) = if (isReturn) apply() else default /** * Returns the value from this Return or throws the exception if this is a Throw */ def apply(): R /** * Returns the value from this Return or throws the exception if this is a Throw. * Alias for apply() */ def get() = apply() /** * Applies the given function f if this is a Result. */ def foreach(f: R => Unit) { onSuccess(f) } /** * Returns the given function applied to the value from this Return or returns this if this is a Throw. * * ''Note'' The gnarly type parameterization is there for Java compatibility, since Java * does not support higher-kinded types. */ def flatMap[R2](f: R => Try[R2]): Try[R2] /** * Maps the given function to the value from this Return or returns this if this is a Throw */ def map[X](f: R => X): Try[X] /** * Returns true if this Try is a Return and the predicate p returns true when * applied to its value. */ def exists(p: R => Boolean): Boolean /** * Converts this to a Throw if the predicate does not obtain. */ def filter(p: R => Boolean): Try[R] /** * Converts this to a Throw if the predicate does not obtain. */ def withFilter(p: R => Boolean): Try[R] /** * Calls the exceptionHandler with the exception if this is a Throw. This is like flatMap for the exception. * * ''Note'' The gnarly type parameterization is there for Java compatibility, since Java * does not support higher-kinded types. */ def rescue[R2 >: R](rescueException: PartialFunction[Throwable, Try[R2]]): Try[R2] /** * Calls the exceptionHandler with the exception if this is a Throw. This is like map for the exception. */ def handle[R2 >: R](rescueException: PartialFunction[Throwable, R2]): Try[R2] /** * Invoked only if the computation was successful. Returns a * chained `this` as in `respond`. */ def onSuccess(f: R => Unit): Try[R] /** * Invoke the function on the error, if the computation was * unsuccessful. Returns a chained `this` as in `respond`. */ def onFailure(rescueException: Throwable => Unit): Try[R] /** * Invoked regardless of whether the computation completed * successfully or unsuccessfully. Implemented in terms of * `respond` so that subclasses control evaluation order. Returns a * chained `this` as in `respond`. */ def ensure(f: => Unit): Try[R] = respond { _ => f } /** * Returns None if this is a Throw or a Some containing the value if this is a Return */ def toOption = if (isReturn) Some(apply()) else None /** * Invokes the given closure when the value is available. Returns * another 'This[R]' that is guaranteed to be available only *after* * 'k' has run. This enables the enforcement of invocation ordering. */ def respond(k: Try[R] => Unit): Try[R] = { k(this); this } /** * Invokes the given transformation when the value is available, * returning the transformed value. This method is like a combination * of flatMap and rescue. This method is typically used for more * imperative control-flow than flatMap/rescue which often exploits * the Null Object Pattern. */ def transform[R2](f: Try[R] => Try[R2]): Try[R2] = f(this) /** * Returns the given function applied to the value from this Return or returns this if this is a Throw. * Alias for flatMap */ def andThen[R2](f: R => Try[R2]) = flatMap(f) def flatten[T](implicit ev: R <:< Try[T]): Try[T] } object Throw { private val NotApplied: Throw[Nothing] = Throw[Nothing](null) private val AlwaysNotApplied: Any => Throw[Nothing] = scala.Function.const(NotApplied) _ } final case class Throw[+R](e: Throwable) extends Try[R] { def isThrow = true def isReturn = false def rescue[R2 >: R](rescueException: PartialFunction[Throwable, Try[R2]]) = { try { val result = rescueException.applyOrElse(e, Throw.AlwaysNotApplied) if (result eq Throw.NotApplied) this else result } catch { case NonFatal(e2) => Throw(e2) } } def apply(): R = throw e def flatMap[R2](f: R => Try[R2]) = this.asInstanceOf[Throw[R2]] def flatten[T](implicit ev: R <:< Try[T]): Try[T] = this.asInstanceOf[Throw[T]] def map[X](f: R => X) = this.asInstanceOf[Throw[X]] def exists(p: R => Boolean) = false def filter(p: R => Boolean) = this def withFilter(p: R => Boolean) = this def onFailure(rescueException: Throwable => Unit) = { rescueException(e); this } def onSuccess(f: R => Unit) = this def handle[R2 >: R](rescueException: PartialFunction[Throwable, R2]) = if (rescueException.isDefinedAt(e)) { Try(rescueException(e)) } else { this } } object Return { val Unit = Return(()) val Void = Return[Void](null) val None: Return[Option[Nothing]] = Return(Option.empty) val Nil: Return[Seq[Nothing]] = Return(Seq.empty) val True: Return[Boolean] = Return(true) val False: Return[Boolean] = Return(false) } final case class Return[+R](r: R) extends Try[R] { def isThrow = false def isReturn = true def rescue[R2 >: R](rescueException: PartialFunction[Throwable, Try[R2]]) = Return(r) def apply() = r def flatMap[R2](f: R => Try[R2]) = try f(r) catch { case NonFatal(e) => Throw(e) } def flatten[T](implicit ev: R <:< Try[T]): Try[T] = r def map[X](f: R => X) = Try[X](f(r)) def exists(p: R => Boolean) = p(r) def filter(p: R => Boolean) = if (p(apply())) this else Throw(new Try.PredicateDoesNotObtain) def withFilter(p: R => Boolean) = filter(p) def onFailure(rescueException: Throwable => Unit) = this def onSuccess(f: R => Unit) = { f(r); this } def handle[R2 >: R](rescueException: PartialFunction[Throwable, R2]) = this }
luciferous/util
util-core/src/main/scala/com/twitter/util/Try.scala
Scala
apache-2.0
7,058
/* Copyright (c) 2015, Robby, Kansas State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sireum.pilar.parser import java.io._ import java.nio.file.Files import java.util.Random import org.sireum.option.PilarParserOption import org.sireum.pilar.ast._ import org.sireum.util._ object Parser { def run(option: PilarParserOption, outPrintln: String => Unit, errPrintln: String => Unit): Boolean = { var printUsage = false val im = PilarParserOption.InputMode val om = PilarParserOption.OutputMode val stdin = option.standardInput var ok = true var inputs = ivectorEmpty[(PilarParserOption.InputMode.Type, File)] val outputFile = option.outputFile.map { o => val f = new File(o) val fParent = f.getParentFile if (!fParent.exists()) { ok = false errPrintln(s"Output directory '${fParent.getPath}' does not exist") } else if (f.exists()) { outPrintln(s"Output file '$o'exists; it will be overwritten") } f } val inputMode = option.inputMode match { case im.Pilar | im.JSON | im.Scala => option.inputMode case im.Auto => if (stdin) { errPrintln(s"Cannot use input mode '${im.Auto}' for standard input") outPrintln(s"Defaulting to '${im.Pilar}'") im.Pilar } else im.Auto case mode => errPrintln(s"'$mode' is not a valid input mode") if (stdin) ok = false else outPrintln(s"Defaulting to '${im.Auto}'") im.Auto } val maxErrors = if (option.maxErrors < 0) { errPrintln("Maximum number of errors cannot be lower than zero") val n = new Random().nextInt(Int.MaxValue) + 1 outPrintln(s"Defaulting to '$n'") n } else { option.maxErrors } val outputMode = if (om.elements.contains(option.outputMode)) option.outputMode else { errPrintln(s"Output mode '${option.outputMode}' is not recognized") val m = om.elements(new Random().nextInt(om.elements.size)) outPrintln(s"Defaulting to '$m'") m } if (option.inputs.nonEmpty) { if (stdin) { outPrintln("Using standard input stream") outPrintln(s"Ignoring input files:") option.inputs.foreach(outPrintln) } else { for (i <- option.inputs) { val f = new File(i) if (f.exists()) { val mode = if (inputMode == im.Auto) { val fname = f.getName val i = fname.lastIndexOf('.') if (i <= 0) im.Auto else { fname.substring(i + 1) match { case "plr" => im.Pilar case "json" => im.JSON case "sc" | "scala" => im.Scala case _ => im.Auto } } } else { option.inputMode } if (mode == im.Auto) { errPrintln(s"Cannot guess input mode for '$i' based on its file extension") outPrintln("Only .plr, .json, .sc, or .scala are recognized") ok = false } inputs = inputs :+(mode, f) } else { ok = false errPrintln(s"Input file '$i' does not exist") } } } } if (ok && !stdin && inputs.isEmpty) { printUsage = true ok = false } if (!ok) return printUsage val inputStrings = if (stdin) ivector((inputMode, _root_.scala.io.Source.stdin.getLines().mkString(System.lineSeparator()))) else inputs.map(f => (f._1, new String(Files.readAllBytes(f._2.toPath)))) val modelOpts = inputStrings.zipWithIndex.map { t => val ((mode, text), i) = t val modelOpt = mode match { case im.Pilar => if (option.antlr4) { Builder(text, maxErrors) } else { FastParser(text, maxErrors) } case im.JSON => try { Some(Pickling.unpickle[Model](text)) } catch { case t: Throwable => errPrintln("Ill-formed JSON input") None } case im.Scala => try { Some(org.sireum.util.reflect.Reflection.eval[Model](text)) } catch { case t: Throwable => errPrintln("Ill-formed Scala input") None } } (modelOpt, i) } val models = modelOpts.toVector.sortBy(_._2).flatMap(_._1) if (models.isEmpty) { errPrintln("No result produced") return false } val model = if (models.size == 1) models.head else models.foldLeft(Model(Node.emptySeq))(_ + _) val result = outputMode match { case om.Pilar => PrettyPrinter(model) case om.Scala => s"""import org.sireum.pilar.ast._ |${ProductUtil.toScalaString(model)} """.stripMargin case om.JSON => Pickling.pickle(model) } outputFile match { case Some(f) => Files.write(f.toPath, result.getBytes) outPrintln(s"Written result to ${option.outputFile.get}") case _ => outPrintln(result) } printUsage } }
sireum/v3
cli/jvm/src/main/scala/org/sireum/pilar/parser/Parser.scala
Scala
bsd-2-clause
6,723
package io.mpjsons import org.scalatest.FlatSpec import org.scalatest.MustMatchers._ // For now singleton objects are not supported! //class User(val name: String) // //case object UserMarcin extends User("Marcin") // //case object UserRegisterMessage // //class SingletonObjectSpec extends FlatSpec { // // "Serializer" must "handle singleton Objects" in { // // val userMarcinJson = MPJson.serialize(UserMarcin) // // userMarcinJson mustBe "{}" // // val deserializedUserMarcin = MPJson.deserialize[AnyRef](userMarcinJson) // // deserializedUserMarcin mustBe UserMarcin // // MPJson.deserialize[User]("{}") // // deserializedUserMarcin mustBe UserMarcin // // try { // MPJson.deserialize[User]( """{"name":"Marcin"}""") // fail("Expected Exception") // } catch { // case _:Exception => () // } // } // // "Serializer" must "handle singleton Objects without value" in { // // val message = MPJson.serialize(UserRegisterMessage) // // message mustBe "{}" // // val deserializedMessage = MPJson.deserialize[AnyRef](message) // // deserializedMessage mustBe UserRegisterMessage // } // //}
marpiec/mpjsons
src/test/scala/io/mpjsons/SingletonObjectTest.scala
Scala
apache-2.0
1,150
package net.particlez import scala.util.Random /** * A square shaped configuration where particle locations are described by integer vectors. * The top left point of the configuration has coordinates (0,0,...,0) the bottom right point is represented by a limits vector provided. * The configuration is filled by the empty particle provided as a parameter. This particle is also used to test whether the particle is active. */ class PosConfiguration(val o: Particle[Pos], val limits: Double*) extends Configuration[Pos] { val beta = 1.0 val origin = Array.fill(limits.size)(0.0) val content = scala.collection.mutable.Map[Pos, Particle[Pos]]() fill(o) def emptyLocations() = locations().filter(l => content(l) == o) def locations() = new PosIterator(limits.map(l => l.toInt).toArray).toList def update() { val activeLocations = locations.filter(l => isActive(content(l))) if (activeLocations.isEmpty) return val currLocation = activeLocations(Random.nextInt(activeLocations.size)) val currParticle = content(currLocation) val maxRadius = content.toList.foldLeft(0.0)((r, e) => if (e._2.radius() > r) e._2.radius else r) val neighborhood = locations().filter(other => currLocation.distance(other) <= maxRadius * 2).map(l => (l -> content(l))).toMap val energyBefore = neighborhood.toList.foldLeft(0.0)((r, e) => r + e._2.evaluate(e._1, neighborhood)) val updatedEntries = currParticle.interact(currLocation, neighborhood) val updatedNeighborhood = neighborhood ++ updatedEntries val energyAfter = updatedNeighborhood.toList.foldLeft(0.0)((r, e) => r + e._2.evaluate(e._1, updatedNeighborhood)) val delta = energyAfter - energyBefore; if (delta <= 0) { content ++= updatedEntries } else if (Random.nextDouble() <= Math.exp(-beta * delta)) { content ++= updatedEntries } } //def isActive(p: Particle[Pos]) = true def isActive(p: Particle[Pos]) = p != o def fill(p: Particle[Pos]): Unit = content ++= locations().map((_ -> p)).toMap } /** A location in the configuration that is represented by a vector of real numbers */ case class Pos(coordinates: Array[Double]) extends Distance[Pos] { val dim: Int = coordinates.size def distance(that: Pos): Double = { if (this.dim != that.dim) throw new IllegalArgumentException("Wrong dimension") var res = 0.0 for (i <- 0 until dim) res += Math.pow(this.coordinates(i) - that.coordinates(i), 2) Math.sqrt(res) } override def equals(that: Any) = this.getClass() == that.getClass() && coordinates.toList == that.asInstanceOf[Pos].coordinates.toList override def hashCode() = coordinates.toList.hashCode() override def toString() = coordinates.mkString("Pos(", ";", ")") } /** A companion object that brings alternative constructor to case class (case classes can not have multiple constructors). */ object Pos { def apply(c: Double*) = new Pos(c.toArray) } /** Iterates through all the integer vectors laying between (0,0,...,0) and the limits vector provided. Needed to traverse configuration locations. */ private class PosIterator(val limits: Array[Int]) extends Iterator[Pos] { limits.foreach(e => if (e <= 0) throw new IllegalStateException("limits elements must be strictly positive")) def this(bounds: Int*) = this(bounds.toArray) var nxt = Array.fill(limits.size)(0) def hasNext() = !nxt.zip(limits).exists(e => e._1 >= e._2) def next(): Pos = { if (!hasNext()) throw new RuntimeException("Iterator has no more elements"); val res = Pos(nxt.map(_.toDouble).toArray) inc(0) res } private def inc(i: Int) { if (i < limits.size) { nxt(i) = nxt(i) + 1 if (nxt(i) == limits(i)) { nxt(i) = 0 inc(i + 1) } } else { nxt = limits } } }
bbiletskyy/particlez
src/main/scala/net/particlez/PosConfiguration.scala
Scala
apache-2.0
3,793
package lila.team import org.joda.time.Period import actorApi._ import akka.actor.ActorSelection import lila.db.api._ import lila.hub.actorApi.forum.MakeTeam import lila.hub.actorApi.timeline.{ Propagate, TeamJoin, TeamCreate } import lila.user.tube.userTube import lila.user.{ User, UserContext } import tube._ final class TeamApi( cached: Cached, notifier: Notifier, forum: ActorSelection, indexer: ActorSelection, timeline: ActorSelection) { val creationPeriod = Period weeks 1 def team(id: String) = $find.byId[Team](id) def request(id: String) = $find.byId[Request](id) def create(setup: TeamSetup, me: User): Option[Fu[Team]] = me.canTeam option { val s = setup.trim val team = Team.make( name = s.name, location = s.location, description = s.description, open = s.isOpen, irc = s.hasIrc, createdBy = me) $insert(team) >> MemberRepo.add(team.id, me.id) >>- { (cached.teamIdsCache invalidate me.id) (forum ! MakeTeam(team.id, team.name)) (indexer ! InsertTeam(team)) (timeline ! Propagate( TeamCreate(me.id, team.id) ).toFollowersOf(me.id)) } inject team } def update(team: Team, edit: TeamEdit, me: User): Funit = edit.trim |> { e => team.copy( location = e.location, description = e.description, open = e.isOpen, irc = e.hasIrc) |> { team => $update(team) >>- (indexer ! InsertTeam(team)) } } def mine(me: User): Fu[List[Team]] = $find.byIds[Team](cached teamIds me.id) def hasCreatedRecently(me: User): Fu[Boolean] = TeamRepo.userHasCreatedSince(me.id, creationPeriod) def requestsWithUsers(team: Team): Fu[List[RequestWithUser]] = for { requests ← RequestRepo findByTeam team.id users ← $find.byOrderedIds[User](requests map (_.user)) } yield requests zip users map { case (request, user) => RequestWithUser(request, user) } def requestsWithUsers(user: User): Fu[List[RequestWithUser]] = for { teamIds ← TeamRepo teamIdsByCreator user.id requests ← RequestRepo findByTeams teamIds users ← $find.byOrderedIds[User](requests map (_.user)) } yield requests zip users map { case (request, user) => RequestWithUser(request, user) } def join(teamId: String)(implicit ctx: UserContext): Fu[Option[Requesting]] = for { teamOption ← $find.byId[Team](teamId) result ← ~(teamOption |@| ctx.me.filter(_.canTeam))({ case (team, user) if team.open => (doJoin(team, user.id) inject Joined(team).some): Fu[Option[Requesting]] case (team, user) => fuccess(Motivate(team).some: Option[Requesting]) }) } yield result def requestable(teamId: String, user: User): Fu[Option[Team]] = for { teamOption ← $find.byId[Team](teamId) able ← teamOption.??(requestable(_, user)) } yield teamOption filter (_ => able) def requestable(team: Team, user: User): Fu[Boolean] = RequestRepo.exists(team.id, user.id).map { _ -> belongsTo(team.id, user.id) } map { case (false, false) => true case _ => false } def createRequest(team: Team, setup: RequestSetup, user: User): Funit = requestable(team, user) flatMap { _ ?? { val request = Request.make(team = team.id, user = user.id, message = setup.message) val rwu = RequestWithUser(request, user) $insert(request) >> (cached.nbRequests remove team.createdBy) } } def processRequest(team: Team, request: Request, accept: Boolean): Funit = for { _ ← $remove(request) _ ← cached.nbRequests remove team.createdBy userOption ← $find.byId[User](request.user) _ ← userOption.filter(_ => accept).??(user => doJoin(team, user.id) >>- notifier.acceptRequest(team, request) ) } yield () def doJoin(team: Team, userId: String): Funit = (!belongsTo(team.id, userId)) ?? { MemberRepo userIdsByTeam team.id flatMap { previousMembers => MemberRepo.add(team.id, userId) >> TeamRepo.incMembers(team.id, +1) >>- { (cached.teamIdsCache invalidate userId) (timeline ! Propagate( TeamJoin(userId, team.id) ).toFollowersOf(userId).toUsers(previousMembers)) } } } recover lila.db.recoverDuplicateKey(e => ()) def quit(teamId: String)(implicit ctx: UserContext): Fu[Option[Team]] = for { teamOption ← $find.byId[Team](teamId) result ← ~(teamOption |@| ctx.me)({ case (team, user) => doQuit(team, user.id) inject team.some }) } yield result def doQuit(team: Team, userId: String): Funit = belongsTo(team.id, userId) ?? { MemberRepo.remove(team.id, userId) >> TeamRepo.incMembers(team.id, -1) >>- (cached.teamIdsCache invalidate userId) } def quitAll(userId: String): Funit = MemberRepo.removeByUser(userId) def kick(team: Team, userId: String): Funit = doQuit(team, userId) def enable(team: Team): Funit = TeamRepo.enable(team) >>- (indexer ! InsertTeam(team)) def disable(team: Team): Funit = TeamRepo.disable(team) >>- (indexer ! RemoveTeam(team.id)) // delete for ever, with members but not forums def delete(team: Team): Funit = $remove(team) >> MemberRepo.removeByteam(team.id) >>- (indexer ! RemoveTeam(team.id)) def belongsTo(teamId: String, userId: String): Boolean = cached.teamIds(userId) contains teamId def owns(teamId: String, userId: String): Fu[Boolean] = TeamRepo ownerOf teamId map (Some(userId) ==) def teamIds(userId: String) = cached teamIds userId def teamName(teamId: String) = cached name teamId def nbRequests(teamId: String) = cached nbRequests teamId def recomputeNbMembers = $enumerate.over[Team]($query.all[Team]) { team => MemberRepo.countByTeam(team.id) flatMap { nb => $update.field[String, Team, Int](team.id, "nbMembers", nb) } } }
ccampo133/lila
modules/team/src/main/TeamApi.scala
Scala
mit
5,910
package org.akoshterek.backgammon.move import org.akoshterek.backgammon.board.PositionClass import org.akoshterek.backgammon.eval.Reward /** * @author Alex * date 20.07.2015. */ object Move extends Ordering[Move] { def compare(x: Move, y: Move): Int = { if (x eq y) { 0 } else if (x.rScore != y.rScore) { // smaller score is 'smaller' move x.rScore.compareTo(y.rScore) } else { // bigger back chequer is 'smaller' move y.backChequer.compareTo(x.backChequer) } } } class Move { var anMove: ChequersMove = new ChequersMove var auch: AuchKey = new AuchKey var cMoves = 0 var cPips = 0 /** scores for this move */ def rScore: Float = arEvalMove.equity /** evaluation for this move */ var arEvalMove: Reward = new Reward() var pc: PositionClass = PositionClass.CLASS_OVER var backChequer = 0 }
akoshterek/MultiGammonJava
multi-gammon-core/src/main/java/org/akoshterek/backgammon/move/Move.scala
Scala
gpl-3.0
876
package utils import java.text.DecimalFormat import models.{Purse, PurseBalance, Transaction} class AmountHelper { def formatAmount(amount: Long): String = { new DecimalFormat("#,###,###,##0").format(amount) } def formatSrcPurseAmount(transaction: Transaction): String = formatTransactionPurse(transaction.srcPurse, transaction.srcPurseBalanceAfter) def formatDstPurseAmount(transaction: Transaction): String = transaction.dstPurse match { case Some(purse) => formatTransactionPurse(purse, transaction.dstPurseBalanceAfter) case None => "" } def formatTransactionPurse(purse: Purse, balanceAfter: Option[PurseBalance]): String = { purse.name + balanceAfter.map(balance => " (" + formatAmount(balance.amount) + ")").getOrElse("") } } object AmountHelper extends AmountHelper
vatt2001/finprocessor
app/utils/AmountHelper.scala
Scala
mit
814
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // scalastyle:off println package org.apache.spark.examples import org.apache.spark.{SparkConf, SparkContext} /** * Executes a roll up-style query against Apache logs. * * Usage: LogQuery [logFile] */ object LogQuery { val exampleApacheLogs = List( """10.10.10.10 - "FRED" [18/Jan/2013:17:56:07 +1100] "GET http://images.com/2013/Generic.jpg | HTTP/1.1" 304 315 "http://referall.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; | GTB7.4; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR | 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR | 3.5.30729; Release=ARP)" "UD-1" - "image/jpeg" "whatever" 0.350 "-" - "" 265 923 934 "" | 62.24.11.25 images.com 1358492167 - Whatup""".stripMargin.split('\\n').mkString, """10.10.10.10 - "FRED" [18/Jan/2013:18:02:37 +1100] "GET http://images.com/2013/Generic.jpg | HTTP/1.1" 304 306 "http:/referall.com" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; | GTB7.4; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR | 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR | 3.5.30729; Release=ARP)" "UD-1" - "image/jpeg" "whatever" 0.352 "-" - "" 256 977 988 "" | 0 73.23.2.15 images.com 1358492557 - Whatup""".stripMargin.split('\\n').mkString ) def main(args: Array[String]): Unit = { val sparkConf = new SparkConf().setAppName("Log Query") val sc = new SparkContext(sparkConf) val dataSet = if (args.length == 1) sc.textFile(args(0)) else sc.parallelize(exampleApacheLogs) // scalastyle:off val apacheLogRegex = """^([\\d.]+) (\\S+) (\\S+) \\[([\\w\\d:/]+\\s[+\\-]\\d{4})\\] "(.+?)" (\\d{3}) ([\\d\\-]+) "([^"]+)" "([^"]+)".*""".r // scalastyle:on /** Tracks the total query count and number of aggregate bytes for a particular group. */ class Stats(val count: Int, val numBytes: Int) extends Serializable { def merge(other: Stats): Stats = new Stats(count + other.count, numBytes + other.numBytes) override def toString: String = "bytes=%s\\tn=%s".format(numBytes, count) } def extractKey(line: String): (String, String, String) = { apacheLogRegex.findFirstIn(line) match { case Some(apacheLogRegex(ip, _, user, dateTime, query, status, bytes, referer, ua)) => if (user != "\\"-\\"") (ip, user, query) else (null, null, null) case _ => (null, null, null) } } def extractStats(line: String): Stats = { apacheLogRegex.findFirstIn(line) match { case Some(apacheLogRegex(ip, _, user, dateTime, query, status, bytes, referer, ua)) => new Stats(1, bytes.toInt) case _ => new Stats(1, 0) } } dataSet.map(line => (extractKey(line), extractStats(line))) .reduceByKey((a, b) => a.merge(b)) .collect().foreach{ case (user, query) => println("%s\\t%s".format(user, query))} sc.stop() } } // scalastyle:on println
lhfei/spark-in-action
spark-3.x/src/main/scala/org/apache/spark/examples/LogQuery.scala
Scala
apache-2.0
3,831
package lib import com.amazonaws.services.simpleworkflow.model.ActivityType import swarmize.Swarm import swarmize.aws.SimpleWorkflowConfig import swarmize.json.SubmittedData import scala.concurrent.Future trait Activity { def name: String def version: String def activityType = new ActivityType().withName(name).withVersion(version) def process(r: SubmittedData): Future[SubmittedData] } object Activity { val all = ExternalActivity.all ::: StoreInElasticsearchActivity :: Nil val allTypes = all map (_.activityType) val lookupByType = all.map(a => a.activityType -> a).toMap.withDefault( t => sys.error("cannot process activity type of " + t) ) val lookupByName = all.map(a => a.name -> a).toMap.withDefault( n => sys.error("cannot process activity name of " + n) ) def registerAll() { allTypes.foreach(SimpleWorkflowConfig.createActivityIfNeeded) } }
FreeSchoolHackers/swarmize
processor/app/lib/Activities.scala
Scala
apache-2.0
901
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.scheduler.cluster import org.apache.spark._ import org.apache.spark.deploy.yarn.{ApplicationMaster, YarnAllocationHandler} import org.apache.spark.util.Utils import org.apache.hadoop.conf.Configuration /** * * This is a simple extension to ClusterScheduler - to ensure that appropriate initialization of ApplicationMaster, etc is done */ private[spark] class YarnClusterScheduler(sc: SparkContext, conf: Configuration) extends ClusterScheduler(sc) { logInfo("Created YarnClusterScheduler") def this(sc: SparkContext) = this(sc, new Configuration()) // Nothing else for now ... initialize application master : which needs sparkContext to determine how to allocate // Note that only the first creation of SparkContext influences (and ideally, there must be only one SparkContext, right ?) // Subsequent creations are ignored - since nodes are already allocated by then. // By default, rack is unknown override def getRackForHost(hostPort: String): Option[String] = { val host = Utils.parseHostPort(hostPort)._1 val retval = YarnAllocationHandler.lookupRack(conf, host) if (retval != null) Some(retval) else None } override def postStartHook() { val sparkContextInitialized = ApplicationMaster.sparkContextInitialized(sc) if (sparkContextInitialized){ // Wait for a few seconds for the slaves to bootstrap and register with master - best case attempt Thread.sleep(3000L) } logInfo("YarnClusterScheduler.postStartHook done") } }
mkolod/incubator-spark
yarn/src/main/scala/org/apache/spark/scheduler/cluster/YarnClusterScheduler.scala
Scala
apache-2.0
2,323
package org.ffmmx.example.androidsqlite2.activity import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.HashMap import scala.collection.mutable.Map import org.ffmmx.example.androidsqlite2.R import org.ffmmx.example.androidsqlite2.business.Note import org.ffmmx.example.androidsqlite2.common.SqlUtil import org.ffmmx.example.androidsqlite2.common.Widgets._ import android.app.Activity import android.app.DatePickerDialog import android.app.DatePickerDialog.OnDateSetListener import android.os.Bundle import android.widget.Button import android.widget.DatePicker import android.widget.EditText import android.widget.ListView import android.widget.SimpleAdapter import org.ffmmx.example.androidsqlite2.common.CommonUtil class NoteActivity extends RichActivity { override def onCreate(savedInstanceState: Bundle): Unit = { super.onCreate(savedInstanceState) setContentView(R.layout.note_activity) val sqlUtil = new SqlUtil(NoteActivity.this) val subjectEdit = getById[EditText](R.id.note_subjectEdit) val contentEdit = getById[EditText](R.id.note_contentEdit) val noteTimeEdit = getById[EditText](R.id.note_noteTime) val dateBtn = getById[Button](R.id.note_dateSelectBtn) val addNoteBtn = getById[Button](R.id.note_addNoteBtn) val noteListView = getById[ListView](R.id.note_noteList) dateBtn.onClick({ val now = Calendar.getInstance() now.setTime(new Date) val datapickDialog = new DatePickerDialog(NoteActivity.this, new OnDateSetListener() { override def onDateSet(view: DatePicker, year: Int, month: Int, day: Int): Unit = { val sdf = new SimpleDateFormat("yyyy-MM-dd") val selectDateCal = Calendar.getInstance() selectDateCal.set(year, month, day) noteTimeEdit.setText(sdf.format(selectDateCal.getTime())) } }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)) datapickDialog.show() }) //初始化列表 val noteListViewData = new java.util.ArrayList[java.util.Map[String, Object]]() val sdf = new SimpleDateFormat("yyyy-MM-dd") val db = sqlUtil.getReadableDatabase() try { val notelist = Note.all(db) notelist.foreach(note => { val map = new HashMap[String, Object]() map.put("itemId", new Integer(note.id)) map.put("itemSubject", note.subject) map.put("itemContent", note.content) map.put("itemNotetime", sdf.format(note.noteDate)) noteListViewData.add(map) }) } catch { case t: Throwable => println(t) } finally { db.close() } val simpleAdapter = new SimpleAdapter(NoteActivity.this, noteListViewData, R.layout.note_list, Array("itemSubject", "itemContent", "itemNotetime"), Array(R.id.notelist_itemSubject, R.id.notelist_itemContent, R.id.notelist_itemNotetime)) noteListView.setAdapter(simpleAdapter) addNoteBtn.onClick({ val note = org.ffmmx.example.androidsqlite2.domain.Note(subject = subjectEdit.getText().toString(), content = contentEdit.getText().toString(), noteDate = sdf.parse(noteTimeEdit.getText().toString()), userid = CommonUtil.currentUser.getId()) val db = sqlUtil.getWritableDatabase() try { Note.add(db, note) noteListViewData.clear() val notelist = Note.all(db) notelist.foreach(note => { val map = new HashMap[String, Object]() map.put("itemId", new Integer(note.id)) map.put("itemSubject", note.subject) map.put("itemContent", note.content) map.put("itemNotetime", sdf.format(note.noteDate)) noteListViewData.add(map) }) val simpleAdapter = new SimpleAdapter(NoteActivity.this, noteListViewData, R.layout.note_list, Array("itemSubject", "itemContent", "itemNotetime"), Array(R.id.notelist_itemSubject, R.id.notelist_itemContent, R.id.notelist_itemNotetime)) noteListView.setAdapter(simpleAdapter) } catch { case t => t.printStackTrace() } finally { db.close() } }) } }
firefoxmmx2/AndroidSqlite
src/org/ffmmx/example/androidsqlite2/activity/NoteActivity.scala
Scala
apache-2.0
4,229
package io.youi.model case class ImageInfo(center: Double, middle: Double, rotation: Double, scale: Double)
outr/youi
core/shared/src/main/scala/io/youi/model/ImageInfo.scala
Scala
mit
109
/* * Copyright (C) 2016-2019 Lightbend Inc. <https://www.lightbend.com> */ import sbt._ import scala.annotation.tailrec import java.net.HttpURLConnection import java.io.BufferedReader import java.io.InputStreamReader object DevModeBuild { val ConnectTimeout = 10000 val ReadTimeout = 10000 def callFoo(): String = makeRequest("http://localhost:9008/services/%2Ffooservice") { conn => val br = new BufferedReader(new InputStreamReader((conn.getInputStream()))) val fooAddress = Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\\n").trim() makeRequest(fooAddress + "/foo") { conn => val br = new BufferedReader(new InputStreamReader((conn.getInputStream()))) Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\\n").trim() } } private def makeRequest[T](uri: String)(body: HttpURLConnection => T): T = { var conn: java.net.HttpURLConnection = null try { val url = new java.net.URL(uri) conn = url.openConnection().asInstanceOf[HttpURLConnection] conn.setConnectTimeout(ConnectTimeout) conn.setReadTimeout(ReadTimeout) conn.getResponseCode // we make this call just to block until a response is returned. body(conn) } finally if (conn != null) conn.disconnect() } }
rcavalcanti/lagom
dev/sbt-plugin/src/sbt-test/sbt-plugin/services-intra-communication/project/Build.scala
Scala
apache-2.0
1,300
package io.waylay.kairosdb.driver import java.io.ByteArrayOutputStream import java.util.zip.GZIPOutputStream import io.waylay.kairosdb.driver.models._ import io.waylay.kairosdb.driver.models.HealthCheckResult._ import io.lemonlabs.uri.typesafe.dsl._ import com.typesafe.scalalogging.StrictLogging import io.waylay.kairosdb.driver.KairosDB._ import io.waylay.kairosdb.driver.models.QueryMetricTagsResponse.TagQueryResponse import io.waylay.kairosdb.driver.models.json.Formats._ import io.waylay.kairosdb.driver.models.QueryResponse.Response import play.api.libs.json._ import play.api.libs.ws.{StandaloneWSClient, StandaloneWSRequest, StandaloneWSResponse, WSAuthScheme} import play.api.libs.ws.DefaultBodyWritables._ import play.api.libs.ws.JsonBodyWritables._ import play.api.libs.ws.JsonBodyReadables._ import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} import scala.concurrent.duration._ import scala.collection.immutable.Seq import scala.collection.compat._ object KairosDB { /** Parent exception for all exceptions this driver may throw */ class KairosDBException(msg: String) extends Exception(msg) /** Thrown when the response by KairosDB can't be parsed */ case class KairosDBResponseParseException(msg: String = "Could not parse KairosDB response", errors: collection.Seq[(JsPath, collection.Seq[JsonValidationError])]) extends KairosDBException(s"""$msg (errors: ${errors.mkString(", ")})""") case class KairosDBResponseException(httpErrorCode:Int, httpStatusText:String, errors: Seq[String]) extends KairosDBException(s"""KairosDB returned HTTP $httpErrorCode ($httpStatusText) (errors: ${errors.mkString(", ")})""") } class KairosDB(wsClient: StandaloneWSClient, config: KairosDBConfig, executionContext: ExecutionContext) extends StrictLogging { implicit val ec = executionContext val url = config.url def listMetricNames: Future[Seq[MetricName]] = { wsClient .url((url / "api" / "v1" / "metricnames").toString()) .applyKairosDBAuth .get() .map { wsRepsonseToResult(json => (json \\ "results").validate[Seq[String]]) } .map(_.map(MetricName)) } def listTagNames: Future[Seq[String]] = { wsClient .url((url / "api" / "v1" / "tagnames").toString()) .applyKairosDBAuth .get() .map { wsRepsonseToResult(json => (json \\ "results").validate[Seq[String]]) } } def listTagValues: Future[Seq[String]] = { wsClient .url((url / "api" / "v1" / "tagvalues").toString()) .applyKairosDBAuth .get() .map( wsRepsonseToResult(json => (json \\ "results").validate[Seq[String]]) ) } def healthStatus: Future[HealthStatusResults] = { wsClient .url((url / "api" / "v1" / "health" / "status").toString()) .applyKairosDBAuth .get() .map { wsRepsonseToResult(_.validate[Seq[String]]) } .map(HealthStatusResults) } def healthCheck: Future[HealthCheckResult] = { wsClient .url((url / "api" / "v1" / "health" / "check").toString()) .withRequestTimeout(10.seconds) .applyKairosDBAuth .get() .map(_.status) .map { case 204 => AllHealthy case _ => Unhealthy } .recover { case _ => Unhealthy } } def version: Future[String] = { wsClient .url((url / "api" / "v1" / "version").toString()) .applyKairosDBAuth .get() .map ( wsRepsonseToResult(json => (json \\ "version").validate[String]) ) } def deleteMetric(metricName: MetricName): Future[Unit] = { wsClient .url((url / "api" / "v1" / "metric" / metricName.name).toString()) .applyKairosDBAuth .delete() .map(emptyWsRepsonseToResult) } def addDataPoints(dataPoints: Seq[DataPoint], gzip: Boolean = false): Future[Unit] = { val body = Json.toJson(dataPoints) logger.debug(Json.prettyPrint(body)) val (actualBody, contentType) = if(gzip){ val buff = new ByteArrayOutputStream() val gzos = new GZIPOutputStream(buff) gzos.write(Json.toBytes(body)) gzos.finish() val gzipBody = buff.toByteArray (gzipBody, "application/gzip") }else{ (Json.toBytes(body), "application/json") } wsClient .url((url / "api" / "v1" / "datapoints").toString()) .applyKairosDBAuth .addHttpHeaders("Content-Type" -> contentType) .post(actualBody) .map(emptyWsRepsonseToResult) } def addDataPoint(dataPoint: DataPoint): Future[Unit] = addDataPoints(Seq(dataPoint)) def queryMetrics(queryMetrics: QueryMetrics): Future[Response] = { val query = Json.toJson(queryMetrics) logger.debug(Json.prettyPrint(query)) wsClient .url((url / "api" / "v1" / "datapoints" / "query").toString()) .applyKairosDBAuth .post(query) .map { wsRepsonseToResult(_.validate[Response]) } } /** You can think of this as the exact same as the query but it leaves off the data and just returns the tag information. * * Note: Currently this is not implemented in the HBase datastore. */ def queryMetricTags(queryMetrics: QueryMetrics): Future[TagQueryResponse] = { val query = Json.toJson(queryMetrics) logger.debug(Json.prettyPrint(query)) wsClient .url((url / "api" / "v1" / "datapoints" / "query" / "tags").toString()) .applyKairosDBAuth .post(query) .map { wsRepsonseToResult(_.validate[TagQueryResponse]) } } /** Delete will perform the query specified in the body and delete all data points returned by the query. Aggregators * and groupers have no effect on which data points are deleted. * * Delete is designed such that you could perform a query, verify that the data points returned are correct, and * issue the delete with that query. * * Note: Delete works for the Cassandra and H2 data store only. */ def deleteDataPoints(queryMetrics: QueryMetrics): Future[Unit] = { val query = Json.toJson(queryMetrics) logger.debug(Json.prettyPrint(query)) wsClient .url((url / "api" / "v1" / "datapoints" / "delete").toString()) .applyKairosDBAuth .post(query) .map(emptyWsRepsonseToResult) } private def getErrors(res: StandaloneWSResponse): Seq[String] = { Try(res.body[JsValue]) match { case Success(json) => (json \\ "errors").validate[Seq[String]].asOpt.to(Seq).flatten case Failure(_) => // not a json response like jetty default 401 Seq.empty } } private implicit class PimpedWSRequest(req: StandaloneWSRequest) { def applyKairosDBAuth: StandaloneWSRequest = { val withAuthOption = for { user <- url.user pass <- url.password } yield req.withAuth(user, pass, WSAuthScheme.BASIC) withAuthOption getOrElse req } } private val emptyWsRepsonseToResult: StandaloneWSResponse => Unit = { case res if res.status == 204 => () case other => throw KairosDBResponseException(other.status, other.statusText, getErrors(other)) } private def wsRepsonseToResult[T](transform: JsValue => JsResult[T], successStatusCode: Int = 200): StandaloneWSResponse => T = { case res if res.status == successStatusCode => Try(res.body[JsValue]) match { case Success(json) => transform(json) match { case JsSuccess(result, jsPath) => result case JsError(errors) => throw KairosDBResponseParseException(errors = errors) } case Failure(e) => throw KairosDBResponseParseException("Failed to parse response body to json", Seq()) } case other => throw KairosDBResponseException(other.status, other.statusText, getErrors(other)) } }
waylayio/kairosdb-scala
src/main/scala/io/waylay/kairosdb/driver/KairosDB.scala
Scala
mit
7,819
package org.openurp.edu.eams.teach.schedule.web.action import org.beangle.commons.collection.Collections import org.beangle.commons.collection.Order import org.beangle.data.jpa.dao.OqlBuilder import org.beangle.commons.lang.BitStrings import org.beangle.commons.lang.Strings import org.beangle.commons.transfer.exporter.PropertyExtractor import org.beangle.struts2.helper.ContextHelper import org.beangle.struts2.helper.Params import org.openurp.edu.eams.base.Building import org.openurp.base.Semester import org.openurp.base.TimeSetting import org.beangle.commons.lang.time.WeekDays import org.openurp.edu.base.Project import org.openurp.edu.base.Student import org.openurp.edu.eams.core.service.TimeSettingService import org.openurp.edu.eams.teach.code.industry.TeachLangType import org.openurp.edu.teach.lesson.Lesson import org.openurp.edu.eams.teach.lesson.helper.LessonSearchHelper import org.openurp.edu.eams.teach.lesson.service.LessonService import org.openurp.edu.eams.teach.lesson.util.CourseActivityDigestor import org.openurp.edu.eams.teach.schedule.service.propertyExtractor.SchedulePropertyExtractor import org.openurp.edu.eams.web.action.common.SemesterSupportAction class ScheduleSearchAction extends SemesterSupportAction { var lessonService: LessonService = _ var timeSettingService: TimeSettingService = _ var lessonSearchHelper: LessonSearchHelper = _ protected override def indexSetting() { val semesterId = getInt("semester.id") if (semesterId != null) ContextHelper.put("semester", entityDao.get(classOf[Semester], semesterId)) val project = getProject put("courseTypes", lessonService.courseTypesOfSemester(Collections.newBuffer[Any](project), getDeparts, getAttribute("semester").asInstanceOf[Semester])) put("teachDepartList", lessonService.teachDepartsOfSemester(Collections.newBuffer[Any](project), getDeparts, getAttribute("semester").asInstanceOf[Semester])) put("stdTypeList", getStdTypes) addBaseCode("languages", classOf[TeachLangType]) put("campuses", project.getCampuses) put("weeks", WeekDays.All) var num = 0 if (null != timeSettingService.getClosestTimeSetting(project, getAttribute("semester").asInstanceOf[Semester], null)) { val timeSetting = timeSettingService.getClosestTimeSetting(project, getAttribute("semester").asInstanceOf[Semester], null).asInstanceOf[org.openurp.base.TimeSetting] if (null != timeSetting && null != timeSetting.getDefaultUnits) { num = timeSetting.getDefaultUnits.size } } put("buildings", baseInfoService.getBaseInfos(classOf[Building])) put("units", num) } override def search(): String = { val lessons = entityDao.search(getQueryBuilder) put("teacherIsNull", getBool("fake.teacher.null")) put("lessons", lessons) val digestor = CourseActivityDigestor.getInstance.setDelimeter("<br>") val arrangeInfo = Collections.newMap[Any] for (oneTask <- lessons) { arrangeInfo.put(oneTask.id.toString, digestor.digest(getTextResource, oneTask, ":day :units :weeks :room")) } put("arrangeInfo", arrangeInfo) forward() } protected override def getQueryBuilder(): OqlBuilder[Lesson] = { val builder = lessonSearchHelper.buildQuery() val std = getLoginStudent if (std != null) { builder.where("lesson.teachDepart=:department", std.majorDepart) } else { builder.where("lesson.teachDepart in (:departments)", getDeparts) } if (Strings.isEmpty(get(Order.ORDER_STR))) builder.orderBy("lesson.no") builder } protected def getPropertyExtractor(): PropertyExtractor = { val weekday = Params.getInt("fake.time.day") var courseUnit = Params.getInt("courseActivity.time.startUnit") var activityWeekStart = Params.getInt("fake.time.weekstart") var activityWeekEnd = Params.getInt("fake.time.weekend") var activityWeekState: java.lang.Long = null if (null != activityWeekStart || null != activityWeekEnd) { if (null == activityWeekStart) activityWeekStart = activityWeekEnd if (null == activityWeekEnd) activityWeekEnd = activityWeekStart if (activityWeekEnd >= activityWeekStart && activityWeekEnd < 52 && activityWeekStart > 0) { val sb = new StringBuilder(Strings.repeat("0", 53)) var i = activityWeekStart while (i <= activityWeekEnd) {sb.setCharAt(i, '1')i += 1 } activityWeekState = BitStrings.binValueOf(sb.toString) } } if (null == courseUnit) courseUnit = Params.getInt("fake.time.unit") val extrator = new SchedulePropertyExtractor(getTextResource, entityDao) extrator.setWeekday(weekday) extrator.setWeekState(activityWeekState) extrator.setCourseUnit(courseUnit) extrator.setBuildingId(getLong("fake.building.id")) extrator } }
openurp/edu-eams-webapp
schedule/src/main/scala/org/openurp/edu/eams/teach/schedule/web/action/ScheduleSearchAction.scala
Scala
gpl-3.0
4,849
package org.scalajs.jsenv object NullJSConsole extends JSConsole { def log(msg: Any): Unit = {} }
jmnarloch/scala-js
js-envs/src/main/scala/org/scalajs/jsenv/NullJSConsole.scala
Scala
bsd-3-clause
101
/* * Copyright (c) 2010 Thorsten Berger <berger@informatik.uni-leipzig.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gsd.buildanalysis.linux import org.kiama.rewriting.Rewriter._ import gsd.common.Logging import model._ import xml.{UnprefixedAttribute, Elem, Node, XML} import java.io.InputStream import gsd.buildanalysis.linux.CFlagRecognition.{CFLAGS_REMOVE_file, CFLAGS_file, FileSpecificCFlags, EXTRA_CFLAGS} object PersistenceManager extends Logging with TreeHelper{ implicit def pimp( elem: Elem ) = new { import scala.xml.Null def %( attrs: Map[String,String] ) = { val seq = for( (n,v) <- attrs ) yield new UnprefixedAttribute( n, v, Null ) ( elem /: seq ) ( _ % _ ) } } def outputXML( root: BNode, targetFile: String ) { info( "Saving Build AST to: " + targetFile ) XML.save( targetFile, getXml( root ) ) } private def getXml( bn: BNode ): Node = ( bn match{ case BNode( RootNode, ch, _, _ ) => <BuildRoot>{ getXml(ch) }</BuildRoot> case BNode( MakefileBNode, ch, _, _ ) => <Makefile>{ getXml(ch) }</Makefile> case BNode( IfBNode, ch, _, _ ) => <If>{ getXml(ch) }</If> case BNode( ObjectBNode, ch, _, _ ) => <Object>{ getXml(ch) }</Object> case BNode( TempReferenceBNode, ch, _, _ ) => <TempReference>{ getXml(ch) }</TempReference> case BNode( TempCompositeListBNode, ch, _, _ ) => <TempCompositeList>{ getXml(ch) }</TempCompositeList> case BNode( VariableDefinitionBNode, ch, _, _ ) => <ListVariableDefinition>{ getXml(ch) }</ListVariableDefinition> case BNode( VariableReferenceBNode, ch, _, _ ) => <VariableReference>{ getXml(ch) }</VariableReference> case BNode( VariableAssignmentBNode, ch, _, _ ) => <VariableAssignment>{ getXml(ch) }</VariableAssignment> case n => sys.error( "Unknown node: " + n ) } ) % getDetails( bn ) % Map( "succ" -> ("" /: (bn->succ))( _ + "," + _.toString ) ) private def getXml( ch: List[BNode] ): Seq[Node] = ch map getXml def getDetails( b: BNode ): Map[String,String] = b match{ case BNode( _, _, exp, details ) => m( exp, "expr" ) ++ ( details match{ case MakefileDetails( mf ) => m( mf, "path" ) case ObjectDetails( oF, bA, ext, gen, lN, sF, fP ) => m( oF, "objectFile" ) ++ m( bA, "builtAs" ) ++ m( ext, "extension" ) ++ m( gen, "generated" ) ++ m( lN, "listName" ) ++ m( sF, "sourceFile" ) ++ m( fP, "fullPathToObject" ) case TempReferenceDetails( v, sS ) => m( v, "variable" ) ++ m( sS, "selectionSuffix" ) case TempCompositeListDetails( lN, s ) => m( lN, "listName" ) ++ m( s, "suffix" ) case VariableReferenceDetails( varName ) => m( varName, "varName" ) case VariableDefinitionDetails( varName ) => m( varName, "varName" ) case VariableAssignmentDetails( n, o, v ) => m( n, "name" ) ++ m( o, "op" ) ++ m( v, "value" ) case _ => Map.empty } ) } private def m[A]( v: Option[A], label: String ): Map[String,String] = v match{ case Some( x ) => m( x, label ) case None => Map.empty } private def m[A]( v: A, label: String ): Map[String,String] = v match{ case e:Expression => Map( label -> pp( e ) ) case _ => Map[String,String]( label -> v.toString ) } def loadManualPCs( is: InputStream ): Map[String,Expression] = { var ret = Map[String,Expression]() val xml = XML load is for( x <- xml.child ) x match{ case <pc>{ _* }</pc> => ret += ( (x\\"f").text -> ExpressionParser.parseString( (x\\"e").text ) ) case _ => ; } ret } def saveCFlags( extra_cflags: List[EXTRA_CFLAGS], fsFlags: List[FileSpecificCFlags], targetFile: String ){ val cflags_file = fsFlags filter( _.isInstanceOf[CFLAGS_file] ) map( _.asInstanceOf[CFLAGS_file] ) val cflags_remove_file = fsFlags filter( _.isInstanceOf[CFLAGS_REMOVE_file] ) map( _.asInstanceOf[CFLAGS_REMOVE_file] ) val xml = <cflags> <EXTRA_CFLAGS_Assignments>{ extra_cflags map{ x => ( x, <EXTRA_CFLAGS value={x.value} op={x.assignmentOp} belongsTo={x.belongsTo}/> ) } map { _ match { case ( EXTRA_CFLAGS(_,_,Some(pc),_), n ) => n % Map( ( "pc" -> pp( pc ) ) ) case ( _, n ) => n }} }</EXTRA_CFLAGS_Assignments> <CFLAGS_file.o>{ cflags_file map{ x => ( x, <CFLAGS value={x.value} op={x.assignmentOp} belongsTo={x.belongsTo}/> ) } map { _ match { case ( y@CFLAGS_file( Some(sf),_,_,_,_), n ) => ( y, n % Map( ( "sourceFile" -> sf ) ) ) case ( y, n ) => (y,n) }} map{ _ match { case ( CFLAGS_file( _,_,_,Some(pc),_), n ) => n % Map( ( "pc" -> pp( pc ) ) ) case ( _, n ) => n }} }</CFLAGS_file.o> <CFLAGS_REMOVE_file.o>{ cflags_remove_file map{ x => ( x, <CFLAGS_REMOVE value={x.value} op={x.assignmentOp} belongsTo={x.belongsTo}/> ) } map { _ match { case ( y@CFLAGS_REMOVE_file( Some(sf),_,_,_,_), n ) => ( y, n % Map( ( "sourceFile" -> sf ) ) ) case ( y, n ) => (y,n) }} map{ _ match { case ( CFLAGS_REMOVE_file( _,_,_,Some(pc),_), n ) => n % Map( ( "pc" -> pp( pc ) ) ) case ( _, n ) => n }} }</CFLAGS_REMOVE_file.o> </cflags> XML.save( targetFile, xml ) } /** * pretty print expression */ def pp( e: Expression ): String = e match{ case BinaryExpression( a, b, s ) => "(" + pp(a) + " " + s + " " + pp(b) + ")" case UnaryExpression( a, s ) => s + pp(a) case UnknownExpression( e ) => "Unknown(" + pp(e) + ")" case Identifier( i ) => i case Defined( id ) => pp( id ) // case Defined( id ) => "defined(" + pp( id ) + ")" case IntLiteral( v ) => v toString case StringLiteral( v ) => "\\"" + v + "\\"" case True() => "[TRUE]" case False() => "[FALSE]" case _ => e toString } }
ckaestne/KBuildMiner
src/main/scala/gsd/buildanalysis/linux/PersistenceManager.scala
Scala
gpl-3.0
6,685
package tbox import org.scalatest.FunSuite class TBoxSpec extends FunSuite { case class Foo(a : String) object Foo { implicit val Foo_ToJson : ToJson[Foo] = new ToJson[Foo] { def toJson(foo : Foo) = s"""{"a":"${foo.a}"}""" } implicit val Foo_Show : Show[Foo] = new Show[Foo] { def show(foo : Foo) = s"""Foo(${foo.a})""" } implicit val Foo_ToBytes : ToBytes[Foo] = new ToBytes[Foo] { def toBytes(foo : Foo) = Array(1, 2, 3) } } case class Bar(b : Int) object Bar { implicit val Bar_ToJson : ToJson[Bar] = new ToJson[Bar] { def toJson(bar : Bar) = s"""{"b":${bar.b}}""" } implicit val Bar_Show : Show[Bar] = new Show[Bar] { def show(bar : Bar) = s"""Bar(${bar.b})""" } implicit val Bar_ToBytes : ToBytes[Bar] = new ToBytes[Bar] { def toBytes(bar : Bar) = Array(4, 5, 6) } } test("TBox should work for simple type-classes.") { val toJsonList : List[TBox[ToJson]] = TBox[ToJson](Foo("hello")) :: TBox[ToJson](Bar(123)) :: Nil assert(toJsonList.map(_.toJson) == List("""{"a":"hello"}""", """{"b":123}""")) } test("TBox2 should work for simple type-classes.") { val hetList : List[TBox2[ToJson, Show]] = TBox2[ToJson, Show](Foo("hello")) :: TBox2[ToJson, Show](Bar(123)) :: Nil assert(hetList.map(_.toJson) == List("""{"a":"hello"}""", """{"b":123}""")) assert(hetList.map(_.show) == List("""Foo(hello)""", """Bar(123)""")) } test("TBox3 should work for simple type-classes.") { val hetList : List[TBox3[ToJson, Show, ToBytes]] = TBox3[ToJson, Show, ToBytes](Foo("hello")) :: TBox3[ToJson, Show, ToBytes](Bar(123)) :: Nil assert(hetList.map(_.toJson) == List("""{"a":"hello"}""", """{"b":123}""")) assert(hetList.map(_.show) == List("""Foo(hello)""", """Bar(123)""")) assert(hetList.map(_.toBytes.toList) == List(List(1, 2, 3), List(4, 5, 6))) } test("TBox should not work for Semigroup.") { assertTypeError("""TBox[Semigroup](5) ++ TBox[Semigroup]("foo")""") } test("TBox should not work for FromInteger.") { assertTypeError("""implicitly[FromInteger[TBox[FromInteger]]]""") } }
ChrisNeveu/TBox
src/test/scala/TBoxTest.scala
Scala
bsd-3-clause
2,253
/* * Licensed to Tuplejump Software Pvt. Ltd. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Tuplejump Software Pvt. Ltd. licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tuplejump.calliope.examples import com.tuplejump.calliope.Types._ import java.util.Date import scala.language.implicitConversions /** * This class demonstrates some Transformer to help you write your own. */ class Transformers { /* * * Always include RichByteBuffer._, it will make your code much cleaner, * as you won't have to deal with the ByteBuffer => T transforms for basic types * */ import com.tuplejump.calliope.utils.RichByteBuffer._ /** * * Let us consider a Cassandra Column Family containing skinny rows for storing employees, * * +---------+------------------------------------------------------------+ * | emp_id | Columns | * +---------+------------------------------------------------------------+ * | | +-----------------+-----------+---------+----------------+ | * | | | name | dept | age | email | | * | | +-----------------+-----------+---------+----------------+ | * | | | * +---------+------------------------------------------------------------+ * * Which will be represented in CQL as, * * +-------------+----------------+-----------+--------------+------------------+ * | emp_id (pk) | name | dept | age | email | * +-------------+----------------+-----------+--------------+------------------+ * * And we would like to work with the Employee case class in our RDDs, * i.e. the RDD created should be RDD[Employee], given * * case class Employee(empId: String, name: String, dept: String, age: Int, email: String) * **/ case class Employee(empId: String, name: String, dept: String, age: Int, email: String) /** * * Using <b>thriftCassandra</b> we need to provide an implicit convertor of type, * (ThriftRowKey, ThriftRowMap) => Employee * * Where * type ThriftRowKey = ByteBuffer * type ThriftColumnName = ByteBuffer * type ThriftColumnValue = ByteBuffer * type ThriftRowMap = Map[ThriftColumnName, ThriftColumnValue] * * i.e. the 'key' will have the emp_id or the thrift key * and the values will have the columns as a Map of name to their value. * * In the method below you'll see we use strings for ColumnNames and * we don't worry about converting the values as ByteBuffer to their data types i.e. * String for empId, name, dept, email and Int for age. This is possible as the implicits in * RichByteBuffer provide us with these transforms. * */ implicit def thriftEmp2Employee(k: ThriftRowKey, v: ThriftRowMap): Employee = { Employee(k, v("name"), v("dept"), v("age"), v("email")) } /** * * Using <b>cql3Cassandra</b> on the same we need to provide an implicit convertor of type, * (CQLRowKeyMap, CQLRowMap) => Employee * * Where * type CQLRowKeyMap = Map[CQLColumnName, CQLColumnValue] * type CQLRowMap = Map[CQLColumnName, CQLColumnValue] * type CQLColumnName = String * type CQLColumnValue = ByteBuffer * * In the method below you'll see we don't worry about converting the values as ByteBuffer to their data types i.e. * String for empId, name, dept, email and Int for age. This is possible as the implicits in * RichByteBuffer provide us with these transforms. * */ implicit def cql3Emp2Employee(k: CQLRowKeyMap, v: CQLRowMap): Employee = { Employee(k("emp_id"), v("name"), v("dept"), v("age"), v("email")) } /** * To write the output of a Spark job which results in RDD[Employee] to this Column Family, we will need to provide * the reverse transformers **/ /** * * Let us first look at how we write this out using <b>thriftSaveToCassandra</b> * This method expects us to provide two implicit transformers of type, * 1. U => ThriftRowKey * 2. U => ThriftRowMap * * As we have a simple Row Key for our table we can emit that as is. * The second function will require return a map for column_name -> column_value * **/ implicit def employee2ThriftRowKey(emp: Employee): ThriftRowKey = { // The row key in the case class Employee is the empId, so we return that emp.empId } implicit def employee2ThriftRowMap(emp: Employee): ThriftRowMap = { // Here we have to return the map for this rows columns. Map( "name" -> emp.name, "dept" -> emp.dept, "age" -> emp.age, "email" -> emp.email ) } /** * * Again, let us do the same with <b>cql3SaveToCassandra</b> * * Before we go to transformers, * note that using this method requires you to configure the saveWithQuery on Cql3CasBuilder. * * The query <b>SHOULD</b> be an <b>UPDATE</b> query setting the values and not specifying the key. * In our case here this will be, * <i>UPDATE empKeyspace.empTable set name = ?, dept = ?, age = ?, email = ?</i> * * * Coming to transformers, in this case we will need 2 transformers, * 1. U => CQLRowKeyMap * 2. U => CQLRowValues * * Where, * type CQLRowKeyMap = Map[CQLColumnName, CQLColumnValue] * type CQLRowValues = List[CQLColumnValue] * type CQLColumnName = String * type CQLColumnValue = ByteBuffer * * Thus we will need a method that take Employee e and return ("emp_id" -> e.empId) * * And Another method that takes Employee e and returns a List(name, dept, age, email) * in the same order as mentioned in the query. * */ implicit def employee2CqlRowKeyMap(emp: Employee): CQLRowKeyMap = { Map("emp_id" -> emp.empId) } implicit def employee2CqlRowValues(emp: Employee): CQLRowValues = { List(emp.name, emp.dept, emp.age, emp.email) } /** * * <b>Let us now take a look at working with wide rows.</b> * We will continue working with the same employee class, but change our, * Cassandra column family to use a wide row model. * For this Let us make dept the partitioning key and emp_id the clustering key. * * So our Column Family will look like this, * * +---------+---------------------------------------------------------------------------------+ * | dept | Columns | * +---------+---------------------------------------------------------------------------------+ * | | +-----------------+----------------+----------------+------------------+----+-- | * | | | [emp_id].name | [emp_id].dept | [emp_id].age | [emp_id].email |... | | * | | +-----------------+----------------+----------------+------------------+----+-- | * | | | * +---------+---------------------------------------------------------------------------------+ * * Which will be represented in CQL as, * * +-----------+-------------+----------------+--------------+------------------+ * | dept (pk) | emp_id (ck) | name | age | email | * +-----------+-------------+----------------+--------------+------------------+ * * In our use and also with our clients we have found that using CQL3 * approach is much more easier to work with wisse rows as the data coming from Cassandra if already transformed * into a map structure. * * Hence, in this scenario we will focus on using the <b>cql3Cassandra</b>. * **/ /** * * To read the data from this column family, we will need a transformer with signature, * (CQLRowKeyMap, CQLRowMap) => Employee * * The difference in this transformer from the last one we used for skinny rows with same signature is * that the CQLRowKeyMap (key) will have <b>dept</b> and <b>emp_id</b> as dept and emp_id are the partition * and clustering keys respectively. * * Notice in the method below we are reading the emp_id and dept from key and rest from the row's value. * **/ implicit def cql3Wide2Employee(key: CQLRowKeyMap, v: CQLRowMap): Employee = { Employee(key("emp_id"), v("name"), key("dept"), v("age"), v("email")) } /** * To write to this column family we will again need the update query setting the values, * * UPDATE empKeyspace.empWideTable set name = ?, age = ?, email = ? * * Notice that we don't have dept in the set clause anymore. * * And now to write the transformers, we again need, 2 transformers, * 1. U => CQLRowKeyMap * 2. U => CQLRowValues * * As will be obvious by now, the first transformer will emit a Map, * with dept and emp_id as the keys mapped to their values. * * The second transformer will emit a list for name, age and email in that order. * */ implicit def employee2CqlRowKeyMapWide(emp: Employee): CQLRowKeyMap = { Map("dept" -> emp.dept, "emp_id" -> emp.empId) } implicit def employee2CqlRowValuesWide(emp: Employee): CQLRowValues = { List(emp.name, emp.age, emp.email) } /** * * Continuing the same story, if name was also part of the key (either partition or clustering) * i.e. the primary key of the column family was defined as * (dept, name, emp_id) or ((dept, name), emp_id) then in our transformer * we would read it from the key i.e. * */ implicit def cql3XWide2Employee(key: CQLRowKeyMap, v: CQLRowMap): Employee = { Employee(key("emp_id"), key("name"), key("dept"), v("age"), v("email")) } /** * * Finally, let us see at a special case of column family with a counter column. * * If we have created a CQL3 CF like this, * * +-----------+--------------+-------------------+ * | fact (pk) | base_ts (ck) | count (counter) | * +-----------+--------------+-------------------+ * * There is nothing different in reading from the ColumnFamily. * So if we are using a case class called FactCount like, * * FactCount(fact: String, baseTs: Date, count: Long) * */ case class FactCount(fact: String, baseTs: Date, count: Long) /** * * The transformer to read, will have the signature, * (CQLRowKeyMap, CQLRowMap) => FactCount * */ implicit def cqlRow2FactCount(k: CQLRowKeyMap, v: CQLRowMap): FactCount = FactCount(k("fact"), k("base_ts"), v("count")) /** * * To write to this column family wee will use the following query, * UPDATE cube.facts set count = count + ? * * as we will want to update the count and cannot just set it. * * And our transformers in this case will be, * */ implicit def factCount2RowMap(fc: FactCount): CQLRowKeyMap = Map("fact" -> fc.fact, "base_ts" -> fc.baseTs) implicit def factCount2RowValues(fc: FactCount): CQLRowValues = List(fc.count) }
brenttheisen/calliope-public
src/main/scala/com/tuplejump/calliope/examples/Transformers.scala
Scala
apache-2.0
11,700
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.stratio.provider.schema import org.apache.spark.sql.types.StructType /** * Knows the way to provide some Data Source schema */ trait SchemaProvider { /** * Provides the schema for current implementation of Data Source * @return schema */ def schema(): StructType }
ccaballe/spark-mongodb
spark-mongodb/src/main/scala/com/stratio/provider/schema/SchemaProvider.scala
Scala
apache-2.0
1,092
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.cluster.sdv.generated import org.apache.spark.sql.common.util._ import org.scalatest.BeforeAndAfterAll import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.util.CarbonProperties /** * Test Class for OffheapSort1TestCase to verify all scenerios */ class OffheapSort1TestCase extends QueryTest with BeforeAndAfterAll { //To load data after setting offheap memory in carbon property file test("OffHeapSort_001-TC_001", Include) { sql(s"""CREATE TABLE uniqdata11 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata11 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','BAD_RECORDS_ACTION'='FORCE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata11""").collect sql(s"""drop table uniqdata11""").collect } //To load 1 lac data load after setting offheap memory in carbon property file test("OffHeapSort_001-TC_002", Include) { sql(s"""CREATE TABLE uniqdata12 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata12 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','BAD_RECORDS_ACTION'='FORCE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata12""").collect sql(s"""drop table uniqdata12""").collect } //To load data after setting offheap memory in carbon property file with option file header in load test("OffHeapSort_001-TC_003", Include) { sql(s"""CREATE TABLE uniqdata12a(CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata12a OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','BAD_RECORDS_ACTION'='FORCE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata12a""").collect sql(s"""drop table uniqdata12a""").collect } //To load data after setting offheap memory in carbon property file without folder path in load test("OffHeapSort_001-TC_004", Include) { intercept[Exception] { sql(s"""CREATE TABLE uniqdata13 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'org.apache.carbondata.format'""").collect sql(s"""LOAD DATA into table uniqdata13 OPTIONS('DELIMITER'=',' , 'FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect } sql(s"""drop table uniqdata13""").collect } //To load data after setting offheap memory in carbon property file without table_name in load test("OffHeapSort_001-TC_005", Include) { sql(s"""drop table if exists uniqdata14""").collect intercept[Exception] { sql(s"""CREATE TABLE uniqdata14 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'org.apache.carbondata.format'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/HeapVector/2000_UniqData.csv' into table OPTIONS('DELIMITER'=',' , 'FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect } sql(s"""drop table if exists uniqdata14""").collect } //To load data after setting offheap memory in carbon property file with option QUOTECHAR'='"' test("OffHeapSort_001-TC_006", Include) { sql(s"""CREATE TABLE uniqdata15 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata15 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata15""").collect sql(s"""drop table uniqdata15""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS('COMMENTCHAR'='#') test("OffHeapSort_001-TC_007", Include) { sql(s"""CREATE TABLE uniqdata16 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata16 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata16""").collect sql(s"""drop table uniqdata16""").collect } //To load data after setting offheap memory in carbon property file with option 'MULTILINE'='true' test("OffHeapSort_001-TC_008", Include) { sql(s"""CREATE TABLE uniqdata17 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata17 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata17""").collect sql(s"""drop table uniqdata17""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS('ESCAPECHAR'='\') test("OffHeapSort_001-TC_009", Include) { sql(s"""CREATE TABLE uniqdata18 (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata18 OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata18""").collect sql(s"""drop table uniqdata18""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS 'BAD_RECORDS_ACTION'='FORCE' test("OffHeapSort_001-TC_010", Include) { sql(s"""CREATE TABLE uniqdata19b (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata19b OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','BAD_RECORDS_ACTION'='FORCE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata19b""").collect sql(s"""drop table uniqdata19b""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS 'BAD_RECORDS_ACTION'='IGNORE' test("OffHeapSort_001-TC_011", Include) { sql(s"""CREATE TABLE uniqdata19c (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata19c OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','BAD_RECORDS_ACTION'='IGNORE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata19c""").collect sql(s"""drop table uniqdata19c""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS 'BAD_RECORDS_ACTION'='REDIRECT' test("OffHeapSort_001-TC_012", Include) { sql(s"""CREATE TABLE uniqdata19d (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata19d OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','BAD_RECORDS_ACTION'='REDIRECT','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata19d""").collect sql(s"""drop table uniqdata19d""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS 'BAD_RECORDS_LOGGER_ENABLE'='FALSE' test("OffHeapSort_001-TC_013", Include) { sql(s"""CREATE TABLE uniqdata19e (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata19e OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','BAD_RECORDS_ACTION'='REDIRECT','BAD_RECORDS_LOGGER_ENABLE'='FALSE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata19e""").collect sql(s"""drop table uniqdata19e""").collect } //To load data after setting offheap memory in carbon property file with OPTIONS 'BAD_RECORDS_LOGGER_ENABLE'='TRUE' test("OffHeapSort_001-TC_014", Include) { sql(s"""CREATE TABLE uniqdata19f (CUST_ID int,CUST_NAME String,ACTIVE_EMUI_VERSION string, DOB timestamp, DOJ timestamp, BIGINT_COLUMN1 bigint,BIGINT_COLUMN2 bigint,DECIMAL_COLUMN1 decimal(30,10), DECIMAL_COLUMN2 decimal(36,10),Double_COLUMN1 double, Double_COLUMN2 double,INTEGER_COLUMN1 int) STORED BY 'carbondata'""").collect sql(s"""LOAD DATA INPATH '$resourcesPath/Data/uniqdata/2000_UniqData.csv' into table uniqdata19f OPTIONS('DELIMITER'=',' , 'QUOTECHAR'='"','COMMENTCHAR'='#','MULTILINE'='true','ESCAPECHAR'='\','BAD_RECORDS_ACTION'='REDIRECT','BAD_RECORDS_LOGGER_ENABLE'='TRUE','FILEHEADER'='CUST_ID,CUST_NAME,ACTIVE_EMUI_VERSION,DOB,DOJ,BIGINT_COLUMN1,BIGINT_COLUMN2,DECIMAL_COLUMN1,DECIMAL_COLUMN2,Double_COLUMN1,Double_COLUMN2,INTEGER_COLUMN1')""").collect sql(s"""select * from uniqdata19f""").collect sql(s"""drop table uniqdata19f""").collect } val prop = CarbonProperties.getInstance() val p1 = prop.getProperty("enable.unsafe.sort", CarbonCommonConstants.ENABLE_UNSAFE_SORT_DEFAULT) val p2 = prop.getProperty("offheap.sort.chunk.size.inmb", CarbonCommonConstants.OFFHEAP_SORT_CHUNK_SIZE_IN_MB_DEFAULT) val p3 = prop.getProperty("sort.inmemory.size.inmb", CarbonCommonConstants.IN_MEMORY_FOR_SORT_DATA_IN_MB_DEFAULT) override protected def beforeAll() { // Adding new properties prop.addProperty("enable.unsafe.sort", "true") prop.addProperty("offheap.sort.chunk.size.inmb", "128") prop.addProperty("sort.inmemory.size.inmb", "1024") } override def afterAll: Unit = { //Reverting to old prop.addProperty("enable.unsafe.sort", p1) prop.addProperty("offheap.sort.chunk.size.inmb", p2) prop.addProperty("sort.inmemory.size.inmb", p3) } }
sgururajshetty/carbondata
integration/spark-common-cluster-test/src/test/scala/org/apache/carbondata/cluster/sdv/generated/OffheapSort1TestCase.scala
Scala
apache-2.0
15,442
def takeWhile_1(f: A => Boolean): Stream[A] = foldRight(empty[A])((h,t) => if (f(h)) cons(h,t) else empty)
ud3sh/coursework
functional-programming-in-scala-textbook/answerkey/laziness/05.answer.scala
Scala
unlicense
122
package vm.interpreter.impl import ea.{NoEscape, ObjectNode} import org.apache.bcel.generic.{BasicType, LDC, ReferenceType} import sai.vm.{DontCare, Reference} import vm.Frame import vm.interpreter.{Id, InstructionInterpreter, InterpreterBuilder} private[interpreter] object LdcInterpreter extends InterpreterBuilder[LDC] { override def apply(i: LDC): InstructionInterpreter = new InstructionInterpreter { override protected[interpreter] def doInterpret(frame: Frame): Frame = { val (newCG, newStack) = i.getType(frame.cpg) match { case objectType: ReferenceType => val node = ObjectNode(Id(frame.method, i)) val updatedCG = frame.cg.addNode(node).updateEscapeState(node -> NoEscape) val updatedStack = frame.stack.push(Reference(objectType, node)) (updatedCG, updatedStack) case _: BasicType => (frame.cg, frame.stack.push(DontCare, i.produceStack(frame.cpg))) } frame.copy(stack = newStack, cg = newCG) } } }
oliverhaase/sai
src/sai/vm/interpreter/impl/LdcInterpreter.scala
Scala
mit
1,010
package pl.writeonly.son2.apis.config import com.fasterxml.jackson.annotation.JsonCreator sealed abstract class WStyle(it: Boolean) extends PartialFunction[Boolean, WStyle] { override def isDefinedAt(x: Boolean): Boolean = x == it override def apply(v1: Boolean): WStyle = this override def toString: String = s"WStyle($it)" } case object WStyle { type T = Boolean => WStyle def get: T = WRaw orElse WPretty def apply(it: Boolean): WStyle = get.apply(it) @JsonCreator def create(it: Boolean): WStyle = apply(it) case object WRaw extends WStyle(false) case object WPretty extends WStyle(true) }
writeonly/son2
scallions-core/scallions-apis/src/main/scala/pl/writeonly/son2/apis/config/WStyle.scala
Scala
apache-2.0
629
/* * Copyright 2016 agido GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pageobject.examples.angularjs.todo object TodoTemplates { val templates = Seq("buy bread", "walk the dog", "go for a walk") }
agido/pageobject
examples/src/test/scala/org/pageobject/examples/angularjs/todo/TodoTemplates.scala
Scala
apache-2.0
735
/* __ *\\ ** ________ ___ / / ___ __ ____ Scala.js Test Suite ** ** / __/ __// _ | / / / _ | __ / // __/ (c) 2013, LAMP/EPFL ** ** __\\ \\/ /__/ __ |/ /__/ __ |/_// /_\\ \\ http://scala-js.org/ ** ** /____/\\___/_/ |_/____/_/ | |__/ /____/ ** ** |/____/ ** \\* */ package org.scalajs.testsuite.niocharset import java.nio._ import java.nio.charset._ import scala.scalajs.niocharset.StandardCharsets import BaseCharsetTest._ abstract class BaseUTF16Test(charset: Charset) extends BaseCharsetTest(charset) { describe(charset.name) { it("decode") { // ASCII characters testDecode(bb"0042 006f 006e 006a 006f 0075 0072")(cb"Bonjour") // Other characters without surrogate pairs testDecode(bb"0047 0072 00fc 00df 0020 0047 006f 0074 0074")(cb"Grüß Gott") testDecode(bb"039a 03b1 03bb 03b7 03bc 03ad 03c1 03b1")(cb"Καλημέρα") testDecode(bb"0635 0628 0627 062d 0020 0627 0644 062e 064a 0631")(cb"صباح الخير") testDecode(bb"3053 3093 306b 3061 306f")(cb"こんにちは") testDecode(bb"0414 043e 0431 0440 044b 0439 0020 0434 0435 043d 044c")(cb"Добрый день") testDecode(bb"4f60 597d")(cb"你好") // 4-byte characters testDecode(bb"d835 dcd7 d835 dcee d835 dcf5 d835 dcf5 d835 dcf8")( cb"\\ud835\\udcd7\\ud835\\udcee\\ud835\\udcf5\\ud835\\udcf5\\ud835\\udcf8") testDecode(bb"")(cb"") // Here begin the sequences with at least one error // Single UTF-16 surrogates testDecode(bb"d800")(Malformed(2)) testDecode(bb"daff")(Malformed(2)) testDecode(bb"db80")(Malformed(2)) testDecode(bb"dbff")(Malformed(2)) testDecode(bb"dc00")(Malformed(2)) testDecode(bb"df80")(Malformed(2)) testDecode(bb"dfff")(Malformed(2)) // High UTF-16 surrogates not followed by low surrogates testDecode(bb"d800 0041")(Malformed(2), cb"A") testDecode(bb"d800 d800")(Malformed(2), Malformed(2)) testDecode(bb"d800 d835 dcd7")(Malformed(2), cb"\\ud835\\udcd7") testDecode(bb"dbff 0041")(Malformed(2), cb"A") testDecode(bb"dbff db8f")(Malformed(2), Malformed(2)) testDecode(bb"dbff d835 dcd7")(Malformed(2), cb"\\ud835\\udcd7") // Lonely byte at the end testDecode(bb"0041 41")(cb"A", Malformed(1)) } it("encode") { // ASCII characters testEncode(cb"Bonjour")(bb"0042 006f 006e 006a 006f 0075 0072") // Other characters without surrogate pairs testEncode(cb"Grüß Gott")(bb"0047 0072 00fc 00df 0020 0047 006f 0074 0074") testEncode(cb"Καλημέρα")(bb"039a 03b1 03bb 03b7 03bc 03ad 03c1 03b1") testEncode(cb"صباح الخير")(bb"0635 0628 0627 062d 0020 0627 0644 062e 064a 0631") testEncode(cb"こんにちは")(bb"3053 3093 306b 3061 306f") testEncode(cb"Добрый день")(bb"0414 043e 0431 0440 044b 0439 0020 0434 0435 043d 044c") testEncode(cb"你好")(bb"4f60 597d") // 4-byte characters testEncode(cb"\\ud835\\udcd7\\ud835\\udcee\\ud835\\udcf5\\ud835\\udcf5\\ud835\\udcf8")( bb"d835 dcd7 d835 dcee d835 dcf5 d835 dcf5 d835 dcf8") testEncode(cb"")(bb"") // Here begin the sequences with at least one error // Single UTF-16 surrogates testEncode(cb"\\ud800")(Malformed(1)) testEncode(cb"\\udaff")(Malformed(1)) testEncode(cb"\\udb80")(Malformed(1)) testEncode(cb"\\udbff")(Malformed(1)) testEncode(cb"\\udc00")(Malformed(1)) testEncode(cb"\\udf80")(Malformed(1)) testEncode(cb"\\udfff")(Malformed(1)) // High UTF-16 surrogates not followed by low surrogates testEncode(cb"\\ud800A")(Malformed(1), bb"0041") testEncode(cb"\\ud800\\ud800")(Malformed(1), Malformed(1)) testEncode(cb"\\ud800\\ud835\\udcd7")(Malformed(1), bb"d835 dcd7") testEncode(cb"\\udbffA")(Malformed(1), bb"0041") testEncode(cb"\\udbff\\udb8f")(Malformed(1), Malformed(1)) testEncode(cb"\\udbff\\ud835\\udcd7")(Malformed(1), bb"d835 dcd7") } } } object UTF16BETest extends BaseUTF16Test(StandardCharsets.UTF_16BE) object UTF16LETest extends BaseUTF16Test(StandardCharsets.UTF_16LE) { override protected def testDecode(in: ByteBuffer)( outParts: OutPart[CharBuffer]*): Unit = { flipByteBuffer(in) super.testDecode(in)(outParts: _*) } override protected def testEncode(in: CharBuffer)( outParts: OutPart[ByteBuffer]*): Unit = { for (BufferPart(buf) <- outParts) flipByteBuffer(buf) super.testEncode(in)(outParts: _*) } /** Flips all pairs of bytes in a byte buffer, except a potential lonely * last byte. */ def flipByteBuffer(buf: ByteBuffer): Unit = { buf.mark() while (buf.remaining() >= 2) { val high = buf.get() val low = buf.get() buf.position(buf.position - 2) buf.put(low) buf.put(high) } buf.reset() } } object UTF16Test extends BaseUTF16Test(StandardCharsets.UTF_16) { def BigEndianBOM = ByteBuffer.wrap(Array(0xfe.toByte, 0xff.toByte)) override protected def testDecode(in: ByteBuffer)( outParts: OutPart[CharBuffer]*): Unit = { // Without BOM, big endian is assumed super.testDecode(in)(outParts: _*) // With BOM, big endian val inWithBOM = ByteBuffer.allocate(2+in.remaining) inWithBOM.put(BigEndianBOM).put(in).flip() super.testDecode(inWithBOM)(outParts: _*) // With BOM, little endian UTF16LETest.flipByteBuffer(inWithBOM) super.testDecode(inWithBOM)(outParts: _*) } override protected def testEncode(in: CharBuffer)( outParts: OutPart[ByteBuffer]*): Unit = { if (in.remaining == 0) super.testEncode(in)(outParts: _*) else super.testEncode(in)(BufferPart(BigEndianBOM) +: outParts: _*) } }
matthughes/scala-js
test-suite/src/test/scala/org/scalajs/testsuite/niocharset/UTF16Test.scala
Scala
bsd-3-clause
5,984
/* * Copyright 2011-2018 GatlingCorp (http://gatling.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gatling.http import scala.concurrent.duration._ import io.gatling.core.Predef._ import io.gatling.http.Predef._ class WsCompileTest extends Simulation { val httpConf = http .baseURL("http://localhost:9000") .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") .doNotTrackHeader("1") .acceptLanguageHeader("en-US,en;q=0.5") .acceptEncodingHeader("gzip, deflate") .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0") .wsBaseURL("ws://localhost:9000") .wsReconnect .wsMaxReconnects(3) val scn = scenario("WebSocket") .exec(http("Home").get("/")) .pause(1) .exec(session => session.set("id", "Steph" + session.userId)) .exec(http("Login").get("/room?username=${id}")) .pause(1) .exec(ws("Connect WS").open("/room/chat?username=${id}")) .pause(1) .repeat(2, "i") { exec(ws("Say Hello WS") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""")).pause(1) } .exec( ws("Message1") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""") .check(wsAwait.within(30 seconds).expect(1).jsonPath("$.message").findAll.saveAs("message1")) ).exec( ws("Message2") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""") .check(wsListen.within(30 seconds).until(1).jsonPath("$.message").saveAs("message2")) ).exec( ws("Message3") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""") .check(wsAwait.within(30 seconds).expect(1).regex("$.message").saveAs("message3")) ).exec( ws("Message3") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""") .check(wsListen.within(30 seconds).expect(1).message) ).exec( ws("Message3") .check(wsListen.within(30 seconds).expect(1).message) ).exec( ws("Cancel").wsName("foo") .cancelCheck ).exec( ws("Message4") .sendText("""{"text": "Hello, I'm ${id} and this is message ${i}!"}""") .check(wsAwait.within(30 seconds).until(1)) ) .exec(ws("Close WS").close) .exec(ws("Open Named", "foo").open("/bar")) setUp(scn.inject(rampUsers(100) over 10)).protocols(httpConf) }
wiacekm/gatling
gatling-http/src/test/scala/io/gatling/http/WsCompileTest.scala
Scala
apache-2.0
3,098
/* * Artificial Intelligence for Humans * Volume 1: Fundamental Algorithms * Scala Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * Copyright 2013 by Jeff Heaton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.general.fns.link;
HairyFotr/aifh
vol1/scala-examples/src/main/scala/com/heatonresearch/aifh/general/fns/link/package.scala
Scala
apache-2.0
989
package gv package isi package convertible trait Conversions extends ImplicitResolutionOrder.Conversions
mouchtaris/jleon
src/main/scala-2.12/gv/isi/convertible/Conversions.scala
Scala
mit
106
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.fixture import org.scalatest._ import SharedHelpers._ import events.TestFailed import org.scalatest.exceptions.DuplicateTestNameException import org.scalatest.exceptions.TestRegistrationClosedException import org.scalatest.events.InfoProvided import org.scalatest.events.MotionToSuppress import org.scalatest.events.IndentedText class WordSpecSpec extends org.scalatest.FunSpec with PrivateMethodTester { describe("A fixture.WordSpec") { it("should return the test names in order of registration from testNames") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "Something" should { "do that" in { fixture => } "do this" in { fixture => } } } assertResult(List("Something should do that", "Something should do this")) { a.testNames.iterator.toList } val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded } assertResult(List[String]()) { b.testNames.iterator.toList } val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "Something" should { "do this" in { fixture => } "do that" in { fixture => } } } assertResult(List("Something should do this", "Something should do that")) { c.testNames.iterator.toList } } it("should throw DuplicateTestNameException if a duplicate test name registration is attempted") { intercept[DuplicateTestNameException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "should test this" in { fixture => } "should test this" in { fixture => } } } intercept[DuplicateTestNameException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "should test this" in { fixture => } "should test this" ignore { fixture => } } } intercept[DuplicateTestNameException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "should test this" ignore { fixture => } "should test this" ignore { fixture => } } } intercept[DuplicateTestNameException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "should test this" ignore { fixture => } "should test this" in { fixture => } } } } it("should pass in the fixture to every test method") { val a = new WordSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "Something" should { "do this" in { fixture => assert(fixture === hello) } "do that" in { fixture => assert(fixture === hello) } } } val rep = new EventRecordingReporter a.run(None, Args(rep)) assert(!rep.eventsReceived.exists(_.isInstanceOf[TestFailed])) } it("should throw NullPointerException if a null test tag is provided") { // it intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(null) in { fixture => } } } val caught = intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(mytags.SlowAsMolasses, null) in { fixture => } } } assert(caught.getMessage === "a test tag was null") intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) in { fixture => } } } // ignore intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(null) ignore { fixture => } } } val caught2 = intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(mytags.SlowAsMolasses, null) ignore { fixture => } } } assert(caught2.getMessage === "a test tag was null") intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "hi" taggedAs(mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) ignore { fixture => } } } // registerTest intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerTest("hi", null) { fixture => } } } val caught3 = intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerTest("hi", mytags.SlowAsMolasses, null) { fixture => } } } assert(caught3.getMessage == "a test tag was null") intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerTest("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => } } } // registerIgnoredTest intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerIgnoredTest("hi", null) { fixture => } } } val caught4 = intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerIgnoredTest("hi", mytags.SlowAsMolasses, null) { fixture => } } } assert(caught4.getMessage == "a test tag was null") intercept[NullPointerException] { new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded registerIgnoredTest("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => } } } } it("should return a correct tags map from the tags method using is (pending)") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" ignore { fixture => } "test that" is (pending) } assertResult(Map("test this" -> Set("org.scalatest.Ignore"))) { a.tags } val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" is (pending) "test that" ignore { fixture => } } assertResult(Map("test that" -> Set("org.scalatest.Ignore"))) { b.tags } val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" ignore { fixture => } "test that" ignore { fixture => } } assertResult(Map("test this" -> Set("org.scalatest.Ignore"), "test that" -> Set("org.scalatest.Ignore"))) { c.tags } val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" taggedAs(mytags.SlowAsMolasses) is (pending) "test that" taggedAs(mytags.SlowAsMolasses) ignore { fixture => } } assertResult(Map("test this" -> Set("org.scalatest.SlowAsMolasses"), "test that" -> Set("org.scalatest.Ignore", "org.scalatest.SlowAsMolasses"))) { d.tags } val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" is (pending) "test that" is (pending) } assertResult(Map()) { e.tags } val f = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" taggedAs(mytags.SlowAsMolasses, mytags.WeakAsAKitten) is (pending) "test that" taggedAs(mytags.SlowAsMolasses) is (pending) } assertResult(Map("test this" -> Set("org.scalatest.SlowAsMolasses", "org.scalatest.WeakAsAKitten"), "test that" -> Set("org.scalatest.SlowAsMolasses"))) { f.tags } val g = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = Succeeded "test this" taggedAs(mytags.SlowAsMolasses, mytags.WeakAsAKitten) is (pending) "test that" taggedAs(mytags.SlowAsMolasses) is (pending) } assertResult(Map("test this" -> Set("org.scalatest.SlowAsMolasses", "org.scalatest.WeakAsAKitten"), "test that" -> Set("org.scalatest.SlowAsMolasses"))) { g.tags } } class TestWasCalledSuite extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "run this" in { fixture => theTestThisCalled = true } "run that, maybe" in { fixture => theTestThatCalled = true } } it("should execute all tests when run is called with testName None") { val b = new TestWasCalledSuite b.run(None, Args(SilentReporter)) assert(b.theTestThisCalled) assert(b.theTestThatCalled) } it("should execute one test when run is called with a defined testName") { val a = new TestWasCalledSuite a.run(Some("run this"), Args(SilentReporter)) assert(a.theTestThisCalled) assert(!a.theTestThatCalled) } it("should report as ignored, and not run, tests marked ignored") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" in { fixture => theTestThisCalled = true } "test that" in { fixture => theTestThatCalled = true } } import scala.language.reflectiveCalls val repA = new TestIgnoredTrackingReporter a.run(None, Args(repA)) assert(!repA.testIgnoredReceived) assert(a.theTestThisCalled) assert(a.theTestThatCalled) val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" ignore { fixture => theTestThisCalled = true } "test that" in { fixture => theTestThatCalled = true } } val repB = new TestIgnoredTrackingReporter b.run(None, Args(repB)) assert(repB.testIgnoredReceived) assert(repB.lastEvent.isDefined) assert(repB.lastEvent.get.testName endsWith "test this") assert(!b.theTestThisCalled) assert(b.theTestThatCalled) val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" in { fixture => theTestThisCalled = true } "test that" ignore { fixture => theTestThatCalled = true } } val repC = new TestIgnoredTrackingReporter c.run(None, Args(repC)) assert(repC.testIgnoredReceived) assert(repC.lastEvent.isDefined) assert(repC.lastEvent.get.testName endsWith "test that", repC.lastEvent.get.testName) assert(c.theTestThisCalled) assert(!c.theTestThatCalled) // The order I want is order of appearance in the file. // Will try and implement that tomorrow. Subtypes will be able to change the order. val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" ignore { fixture => theTestThisCalled = true } "test that" ignore { fixture => theTestThatCalled = true } } val repD = new TestIgnoredTrackingReporter d.run(None, Args(repD)) assert(repD.testIgnoredReceived) assert(repD.lastEvent.isDefined) assert(repD.lastEvent.get.testName endsWith "test that") // last because should be in order of appearance assert(!d.theTestThisCalled) assert(!d.theTestThatCalled) } it("should ignore a test marked as ignored if run is invoked with that testName") { // If I provide a specific testName to run, then it should ignore an Ignore on that test // method and actually invoke it. val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" ignore { fixture => theTestThisCalled = true } "test that" in { fixture => theTestThatCalled = true } } import scala.language.reflectiveCalls val repE = new TestIgnoredTrackingReporter e.run(Some("test this"), Args(repE)) assert(repE.testIgnoredReceived) assert(!e.theTestThisCalled) assert(!e.theTestThatCalled) } it("should run only those tests selected by the tags to include and exclude sets") { // Nothing is excluded val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThisCalled = true } "test that" in { fixture => theTestThatCalled = true } } import scala.language.reflectiveCalls val repA = new TestIgnoredTrackingReporter a.run(None, Args(repA)) assert(!repA.testIgnoredReceived) assert(a.theTestThisCalled) assert(a.theTestThatCalled) // SlowAsMolasses is included, one test should be excluded val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThisCalled = true } "test that" in { fixture => theTestThatCalled = true } } val repB = new TestIgnoredTrackingReporter b.run(None, Args(repB, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repB.testIgnoredReceived) assert(b.theTestThisCalled) assert(!b.theTestThatCalled) // SlowAsMolasses is included, and both tests should be included val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } } val repC = new TestIgnoredTrackingReporter c.run(None, Args(repB, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repC.testIgnoredReceived) assert(c.theTestThisCalled) assert(c.theTestThatCalled) // SlowAsMolasses is included. both tests should be included but one ignored val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false "test this" taggedAs(mytags.SlowAsMolasses) ignore { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } } val repD = new TestIgnoredTrackingReporter d.run(None, Args(repD, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.Ignore")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(repD.testIgnoredReceived) assert(!d.theTestThisCalled) assert(d.theTestThatCalled) // SlowAsMolasses included, FastAsLight excluded val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) in { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } "test the other" in { fixture => theTestTheOtherCalled = true } } val repE = new TestIgnoredTrackingReporter e.run(None, Args(repE, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repE.testIgnoredReceived) assert(!e.theTestThisCalled) assert(e.theTestThatCalled) assert(!e.theTestTheOtherCalled) // An Ignored test that was both included and excluded should not generate a TestIgnored event val f = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) ignore { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } "test the other" in { fixture => theTestTheOtherCalled = true } } val repF = new TestIgnoredTrackingReporter f.run(None, Args(repF, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repF.testIgnoredReceived) assert(!f.theTestThisCalled) assert(f.theTestThatCalled) assert(!f.theTestTheOtherCalled) // An Ignored test that was not included should not generate a TestIgnored event val g = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) in { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } "test the other" ignore { fixture => theTestTheOtherCalled = true } } val repG = new TestIgnoredTrackingReporter g.run(None, Args(repG, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repG.testIgnoredReceived) assert(!g.theTestThisCalled) assert(g.theTestThatCalled) assert(!g.theTestTheOtherCalled) // No tagsToInclude set, FastAsLight excluded val h = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) in { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } "test the other" in { fixture => theTestTheOtherCalled = true } } val repH = new TestIgnoredTrackingReporter h.run(None, Args(repH, Stopper.default, Filter(None, Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repH.testIgnoredReceived) assert(!h.theTestThisCalled) assert(h.theTestThatCalled) assert(h.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded val i = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) in { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => theTestThatCalled = true } "test the other" in { fixture => theTestTheOtherCalled = true } } val repI = new TestIgnoredTrackingReporter i.run(None, Args(repI, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repI.testIgnoredReceived) assert(!i.theTestThisCalled) assert(!i.theTestThatCalled) assert(i.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded, TestIgnored should not be received on excluded ones val j = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) ignore { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) ignore { fixture => theTestThatCalled = true } "test the other" in { fixture => theTestTheOtherCalled = true } } val repJ = new TestIgnoredTrackingReporter j.run(None, Args(repJ, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repI.testIgnoredReceived) assert(!j.theTestThisCalled) assert(!j.theTestThatCalled) assert(j.theTestTheOtherCalled) // Same as previous, except Ignore specifically mentioned in excludes set val k = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false "test this" taggedAs(mytags.SlowAsMolasses, mytags.FastAsLight) ignore { fixture => theTestThisCalled = true } "test that" taggedAs(mytags.SlowAsMolasses) ignore { fixture => theTestThatCalled = true } "test the other" ignore { fixture => theTestTheOtherCalled = true } } val repK = new TestIgnoredTrackingReporter k.run(None, Args(repK, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses", "org.scalatest.Ignore")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(repK.testIgnoredReceived) assert(!k.theTestThisCalled) assert(!k.theTestThatCalled) assert(!k.theTestTheOtherCalled) } it("should run only those registered tests selected by the tags to include and exclude sets") { // Nothing is excluded val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false registerTest("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } registerTest("test that") { fixture => theTestThatCalled = true } } import scala.language.reflectiveCalls val repA = new TestIgnoredTrackingReporter a.run(None, Args(repA)) assert(!repA.testIgnoredReceived) assert(a.theTestThisCalled) assert(a.theTestThatCalled) // SlowAsMolasses is included, one test should be excluded val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false registerTest("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } registerTest("test that") { fixture => theTestThatCalled = true } } val repB = new TestIgnoredTrackingReporter b.run(None, Args(repB, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repB.testIgnoredReceived) assert(b.theTestThisCalled) assert(!b.theTestThatCalled) // SlowAsMolasses is included, and both tests should be included val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false registerTest("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } } val repC = new TestIgnoredTrackingReporter c.run(None, Args(repB, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repC.testIgnoredReceived) assert(c.theTestThisCalled) assert(c.theTestThatCalled) // SlowAsMolasses is included. both tests should be included but one ignored val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false registerIgnoredTest("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } } val repD = new TestIgnoredTrackingReporter d.run(None, Args(repD, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.Ignore")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(repD.testIgnoredReceived) assert(!d.theTestThisCalled) assert(d.theTestThatCalled) // SlowAsMolasses included, FastAsLight excluded val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerTest("test the other") { fixture => theTestTheOtherCalled = true } } val repE = new TestIgnoredTrackingReporter e.run(None, Args(repE, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repE.testIgnoredReceived) assert(!e.theTestThisCalled) assert(e.theTestThatCalled) assert(!e.theTestTheOtherCalled) // An Ignored test that was both included and excluded should not generate a TestIgnored event val f = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerIgnoredTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerTest("test the other") { fixture => theTestTheOtherCalled = true } } val repF = new TestIgnoredTrackingReporter f.run(None, Args(repF, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repF.testIgnoredReceived) assert(!f.theTestThisCalled) assert(f.theTestThatCalled) assert(!f.theTestTheOtherCalled) // An Ignored test that was not included should not generate a TestIgnored event val g = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerIgnoredTest("test the other") { fixture => theTestTheOtherCalled = true } } val repG = new TestIgnoredTrackingReporter g.run(None, Args(repG, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repG.testIgnoredReceived) assert(!g.theTestThisCalled) assert(g.theTestThatCalled) assert(!g.theTestTheOtherCalled) // No tagsToInclude set, FastAsLight excluded val h = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerTest("test the other") { fixture => theTestTheOtherCalled = true } } val repH = new TestIgnoredTrackingReporter h.run(None, Args(repH, Stopper.default, Filter(None, Set("org.scalatest.FastAsLight")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repH.testIgnoredReceived) assert(!h.theTestThisCalled) assert(h.theTestThatCalled) assert(h.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded val i = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerTest("test the other") { fixture => theTestTheOtherCalled = true } } val repI = new TestIgnoredTrackingReporter i.run(None, Args(repI, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repI.testIgnoredReceived) assert(!i.theTestThisCalled) assert(!i.theTestThatCalled) assert(i.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded, TestIgnored should not be received on excluded ones val j = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerIgnoredTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerIgnoredTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerTest("test the other") { fixture => theTestTheOtherCalled = true } } val repJ = new TestIgnoredTrackingReporter j.run(None, Args(repJ, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!repI.testIgnoredReceived) assert(!j.theTestThisCalled) assert(!j.theTestThatCalled) assert(j.theTestTheOtherCalled) // Same as previous, except Ignore specifically mentioned in excludes set val k = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false registerIgnoredTest("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } registerIgnoredTest("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } registerIgnoredTest("test the other") { fixture => theTestTheOtherCalled = true } } val repK = new TestIgnoredTrackingReporter k.run(None, Args(repK, Stopper.default, Filter(None, Set("org.scalatest.SlowAsMolasses", "org.scalatest.Ignore")), ConfigMap.empty, None, new Tracker, Set.empty)) assert(repK.testIgnoredReceived) assert(!k.theTestThisCalled) assert(!k.theTestThatCalled) assert(!k.theTestTheOtherCalled) } it("should return the correct test count from its expectedTestCount method") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "test this" in { fixture => } "test that" in { fixture => } } assert(a.expectedTestCount(Filter()) === 2) val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "test this" ignore { fixture => } "test that" in { fixture => } } assert(b.expectedTestCount(Filter()) === 1) val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "test this" taggedAs(mytags.FastAsLight) in { fixture => } "test that" in { fixture => } } assert(c.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(c.expectedTestCount(Filter(None, Set("org.scalatest.FastAsLight"))) === 1) val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "test this" taggedAs(mytags.FastAsLight, mytags.SlowAsMolasses) in { fixture => } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => } "test the other thing" in { fixture => } } assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1) assert(d.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 1) assert(d.expectedTestCount(Filter()) === 3) val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "test this" taggedAs(mytags.FastAsLight, mytags.SlowAsMolasses) in { fixture => } "test that" taggedAs(mytags.SlowAsMolasses) in { fixture => } "test the other thing" ignore { fixture => } } assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1) assert(e.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 0) assert(e.expectedTestCount(Filter()) === 2) val f = new Suites(a, b, c, d, e) assert(f.expectedTestCount(Filter()) === 10) } it("should return the correct test count from its expectedTestCount method when uses registerTest and registerIgnoredTest to register tests") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("test this") { fixture => } registerTest("test that") { fixture => } } assert(a.expectedTestCount(Filter()) == 2) val b = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerIgnoredTest("test this") { fixture => } registerTest("test that") { fixture => } } assert(b.expectedTestCount(Filter()) == 1) val c = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("test this", mytags.FastAsLight) { fixture => } registerTest("test that") { fixture => } } assert(c.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) == 1) assert(c.expectedTestCount(Filter(None, Set("org.scalatest.FastAsLight"))) == 1) val d = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => } registerTest("test that", mytags.SlowAsMolasses) { fixture => } registerTest("test the other thing") { fixture => } } assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) == 1) assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) == 1) assert(d.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) == 1) assert(d.expectedTestCount(Filter()) == 3) val e = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => } registerTest("test that", mytags.SlowAsMolasses) { fixture => } registerIgnoredTest("test the other thing") { fixture => } } assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) == 1) assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) == 1) assert(e.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) == 0) assert(e.expectedTestCount(Filter()) == 2) val f = new Suites(a, b, c, d, e) assert(f.expectedTestCount(Filter()) == 10) } it("should generate a TestPending message when the test body is (pending)") { val a = new WordSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "should do this" is (pending) "should do that" in { fixture => assert(fixture === hello) } "should do something else" in { fixture => assert(fixture === hello) pending } } val rep = new EventRecordingReporter a.run(None, Args(rep)) val tp = rep.testPendingEventsReceived assert(tp.size === 2) } it("should generate a test failure if a Throwable, or an Error other than direct Error subtypes " + "known in JDK 1.5, excluding AssertionError") { val a = new WordSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "This WordSpec" should { "throw AssertionError" in { s => throw new AssertionError } "throw plain old Error" in { s => throw new Error } "throw Throwable" in { s => throw new Throwable } } } val rep = new EventRecordingReporter a.run(None, Args(rep)) val tf = rep.testFailedEventsReceived assert(tf.size === 3) } it("should propagate out Errors that are direct subtypes of Error in JDK 1.5, other than " + "AssertionError, causing Suites and Runs to abort.") { val a = new WordSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "This WordSpec" should { "throw AssertionError" in { s => throw new OutOfMemoryError } } } intercept[OutOfMemoryError] { a.run(None, Args(SilentReporter)) } } /* it("should send InfoProvided events with aboutAPendingTest set to true for info " + "calls made from a test that is pending") { val a = new WordSpec with GivenWhenThen { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "A WordSpec" should { "do something" in { s => given("two integers") when("one is subracted from the other") then("the result is the difference between the two numbers") pending } } } val rep = new EventRecordingReporter a.run(None, Args(rep)) val testPending = rep.testPendingEventsReceived assert(testPending.size === 1) val recordedEvents = testPending(0).recordedEvents assert(recordedEvents.size === 3) for (event <- recordedEvents) { val ip = event.asInstanceOf[InfoProvided] assert(ip.aboutAPendingTest.isDefined && ip.aboutAPendingTest.get) } val so = rep.scopeOpenedEventsReceived assert(so.size === 1) for (event <- so) { assert(event.message == "A WordSpec") } val sc = rep.scopeClosedEventsReceived assert(so.size === 1) for (event <- sc) { assert(event.message == "A WordSpec") } } it("should send InfoProvided events with aboutAPendingTest set to false for info " + "calls made from a test that is not pending") { val a = new WordSpec with GivenWhenThen { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest): Outcome = { test(hello) } "A WordSpec" should { "do something" in { s => given("two integers") when("one is subracted from the other") then("the result is the difference between the two numbers") assert(1 + 1 === 2) } } } val rep = new EventRecordingReporter a.run(None, Args(rep)) val testSucceeded = rep.testSucceededEventsReceived assert(testSucceeded.size === 1) val recordedEvents = testSucceeded(0).recordedEvents assert(recordedEvents.size === 3) for (event <- recordedEvents) { val ip = event.asInstanceOf[InfoProvided] assert(ip.aboutAPendingTest.isDefined && !ip.aboutAPendingTest.get) } val so = rep.scopeOpenedEventsReceived assert(so.size === 1) for (event <- so) { assert(event.message == "A WordSpec") } val sc = rep.scopeClosedEventsReceived assert(so.size === 1) for (event <- sc) { assert(event.message == "A WordSpec") } } */ it("should allow both tests that take fixtures and tests that don't") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("Hello, world!") } var takesNoArgsInvoked = false var takesAFixtureInvoked = false "A WordSpec" should { "take no args" in { () => takesNoArgsInvoked = true } "take a fixture" in { s => takesAFixtureInvoked = true } } } import scala.language.reflectiveCalls a.run(None, Args(SilentReporter)) assert(a.testNames.size === 2, a.testNames) assert(a.takesNoArgsInvoked) assert(a.takesAFixtureInvoked) } it("should work with test functions whose inferred result type is not Unit") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("Hello, world!") } var takesNoArgsInvoked = false var takesAFixtureInvoked = false "A WordSpec" should { "take no args" in { () => takesNoArgsInvoked = true; true } "take a fixture" in { s => takesAFixtureInvoked = true; true } } } import scala.language.reflectiveCalls assert(!a.takesNoArgsInvoked) assert(!a.takesAFixtureInvoked) a.run(None, Args(SilentReporter)) assert(a.testNames.size === 2, a.testNames) assert(a.takesNoArgsInvoked) assert(a.takesAFixtureInvoked) } it("should work with ignored tests whose inferred result type is not Unit") { val a = new WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } var takeNoArgsInvoked = false var takeAFixtureInvoked = false "A WordSpec" should { "take no args" ignore { () => takeNoArgsInvoked = true; "hi" } "take a fixture" ignore { s => takeAFixtureInvoked = true; 42 } } } import scala.language.reflectiveCalls assert(!a.takeNoArgsInvoked) assert(!a.takeAFixtureInvoked) val reporter = new EventRecordingReporter a.run(None, Args(reporter)) assert(reporter.testIgnoredEventsReceived.size === 2) assert(!a.takeNoArgsInvoked) assert(!a.takeAFixtureInvoked) } it("should pass a NoArgTest to withFixture for tests that take no fixture") { class MySpec extends WordSpec { type FixtureParam = String var aNoArgTestWasPassed = false var aOneArgTestWasPassed = false override def withFixture(test: NoArgTest): Outcome = { aNoArgTestWasPassed = true Succeeded } def withFixture(test: OneArgTest): Outcome = { aOneArgTestWasPassed = true Succeeded } "do something" in { () => assert(1 + 1 === 2) } } val s = new MySpec s.run(None, Args(SilentReporter)) assert(s.aNoArgTestWasPassed) assert(!s.aOneArgTestWasPassed) } it("should not pass a NoArgTest to withFixture for tests that take a Fixture") { class MySpec extends WordSpec { type FixtureParam = String var aNoArgTestWasPassed = false var aOneArgTestWasPassed = false override def withFixture(test: NoArgTest): Outcome = { aNoArgTestWasPassed = true Succeeded } def withFixture(test: OneArgTest): Outcome = { aOneArgTestWasPassed = true Succeeded } "do something" in { fixture => assert(1 + 1 === 2) } } val s = new MySpec s.run(None, Args(SilentReporter)) assert(!s.aNoArgTestWasPassed) assert(s.aOneArgTestWasPassed) } it("should pass a NoArgTest that invokes the no-arg test when the " + "NoArgTest's no-arg apply method is invoked") { class MySpec extends WordSpec { type FixtureParam = String var theNoArgTestWasInvoked = false def withFixture(test: OneArgTest): Outcome = { // Shouldn't be called, but just in case don't invoke a OneArgTest Succeeded } "do something" in { () => theNoArgTestWasInvoked = true } } val s = new MySpec s.run(None, Args(SilentReporter)) assert(s.theNoArgTestWasInvoked) } it("should pass the correct test name in the OneArgTest passed to withFixture") { val a = new WordSpec { type FixtureParam = String var correctTestNameWasPassed = false def withFixture(test: OneArgTest): Outcome = { correctTestNameWasPassed = test.name == "do something" test("hi") } "do something" in { fixture => } } import scala.language.reflectiveCalls a.run(None, Args(SilentReporter)) assert(a.correctTestNameWasPassed) } it("should pass the correct config map in the OneArgTest passed to withFixture") { val a = new WordSpec { type FixtureParam = String var correctConfigMapWasPassed = false def withFixture(test: OneArgTest): Outcome = { correctConfigMapWasPassed = (test.configMap == ConfigMap("hi" -> 7)) test("hi") } "do something" in { fixture => } } import scala.language.reflectiveCalls a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> 7), None, new Tracker(), Set.empty)) assert(a.correctConfigMapWasPassed) } describe("(when a nesting rule has been violated)") { it("should, if they call a should from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" should { } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"should\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a should with a nested in from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" should { "should never run" in { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"should\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a when from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" when { } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"when\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a when with a nested in from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" when { "should never run" in { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"when\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a that from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" that { } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"that\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a that with a nested in from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" that { "should never run" in { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"that\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a which from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" which { } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"which\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a which with a nested in from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" which { "should never run" in { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"which\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a can from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" can { } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"can\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a can with a nested in from within an in clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" can { "should never run" in { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceivedWithCorrectMessage(spec, "should blow up", "a \\"can\\" clause may not appear inside an \\"in\\" clause") } it("should, if they call a nested it from within an it clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "should never run" in { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a nested it with tags from within an it clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "should never run" taggedAs(mytags.SlowAsMolasses) in { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a nested registerTest with tags from within a registerTest clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("should blow up") { fixture => registerTest("should never run", mytags.SlowAsMolasses) { fixture => assert(1 == 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a describe with a nested ignore from within an it clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "in the wrong place, at the wrong time" should { "should never run" ignore { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a nested ignore from within an it clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "should never run" ignore { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a nested ignore with tags from within an it clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "should blow up" in { fixture => "should never run" taggedAs(mytags.SlowAsMolasses) ignore { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } it("should, if they call a nested registerIgnoredTest with tags from within a registerTest clause, result in a TestFailedException when running the test") { class MySpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } registerTest("should blow up") { fixture => registerIgnoredTest("should never run", mytags.SlowAsMolasses) { fixture => assert(1 == 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "should blow up") } } it("should contains correct formatter for TestStarting, TestSucceeded, TestFailed, TestPending, TestCanceled and TestIgnored") { class TestSpec extends WordSpec with StringFixture { "a feature" should { "succeeded here" in { fixture => } "failed here" in { fixture => fail } "pending here" in { fixture => pending } "cancel here" in { fixture => cancel } "ignore here" ignore { fixture => } } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) val testStartingList = rep.testStartingEventsReceived assert(testStartingList.size === 4) assert(testStartingList(0).formatter === Some(MotionToSuppress), "Expected testStartingList(0).formatter to be Some(MotionToSuppress), but got: " + testStartingList(0).formatter.getClass.getName) assert(testStartingList(1).formatter === Some(MotionToSuppress), "Expected testStartingList(1).formatter to be Some(MotionToSuppress), but got: " + testStartingList(1).formatter.getClass.getName) assert(testStartingList(2).formatter === Some(MotionToSuppress), "Expected testStartingList(2).formatter to be Some(MotionToSuppress), but got: " + testStartingList(2).formatter.getClass.getName) assert(testStartingList(3).formatter === Some(MotionToSuppress), "Expected testStartingList(3).formatter to be Some(MotionToSuppress), but got: " + testStartingList(3).formatter.getClass.getName) val testSucceededList = rep.testSucceededEventsReceived assert(testSucceededList.size === 1) assert(testSucceededList(0).formatter.isDefined, "Expected testSucceededList(0).formatter to be defined, but it is not.") assert(testSucceededList(0).formatter.get.isInstanceOf[IndentedText], "Expected testSucceededList(0).formatter to be Some(IndentedText), but got: " + testSucceededList(0).formatter) val testSucceededFormatter = testSucceededList(0).formatter.get.asInstanceOf[IndentedText] assert(testSucceededFormatter.formattedText === "- should succeeded here") assert(testSucceededFormatter.rawText === "should succeeded here") val testFailedList = rep.testFailedEventsReceived assert(testFailedList.size === 1) assert(testFailedList(0).formatter.isDefined, "Expected testFailedList(0).formatter to be defined, but it is not.") assert(testFailedList(0).formatter.get.isInstanceOf[IndentedText], "Expected testFailedList(0).formatter to be Some(IndentedText), but got: " + testSucceededList(0).formatter) val testFailedFormatter = testFailedList(0).formatter.get.asInstanceOf[IndentedText] assert(testFailedFormatter.formattedText === "- should failed here") assert(testFailedFormatter.rawText === "should failed here") val testPendingList = rep.testPendingEventsReceived assert(testPendingList.size === 1) assert(testPendingList(0).formatter.isDefined, "Expected testPendingList(0).formatter to be defined, but it is not.") assert(testPendingList(0).formatter.get.isInstanceOf[IndentedText], "Expected testPendingList(0).formatter to be Some(IndentedText), but got: " + testSucceededList(0).formatter) val testPendingFormatter = testPendingList(0).formatter.get.asInstanceOf[IndentedText] assert(testPendingFormatter.formattedText === "- should pending here") assert(testPendingFormatter.rawText === "should pending here") val testCanceledList = rep.testCanceledEventsReceived assert(testCanceledList.size === 1) assert(testCanceledList(0).formatter.isDefined, "Expected testCanceledList(0).formatter to be defined, but it is not.") assert(testCanceledList(0).formatter.get.isInstanceOf[IndentedText], "Expected testCanceledList(0).formatter to be Some(IndentedText), but got: " + testSucceededList(0).formatter) val testCanceledFormatter = testCanceledList(0).formatter.get.asInstanceOf[IndentedText] assert(testCanceledFormatter.formattedText === "- should cancel here") assert(testCanceledFormatter.rawText === "should cancel here") val testIgnoredList = rep.testIgnoredEventsReceived assert(testIgnoredList.size === 1) assert(testIgnoredList(0).formatter.isDefined, "Expected testIgnoredList(0).formatter to be defined, but it is not.") assert(testIgnoredList(0).formatter.get.isInstanceOf[IndentedText], "Expected testIgnoredList(0).formatter to be Some(IndentedText), but got: " + testSucceededList(0).formatter) val testIgnoredFormatter = testIgnoredList(0).formatter.get.asInstanceOf[IndentedText] assert(testIgnoredFormatter.formattedText === "- should ignore here") assert(testIgnoredFormatter.rawText === "should ignore here") } describe("registerTest and registerIgnoredTest method") { it("should allow test registration and ignored test registration") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = test("test") val a = 1 registerTest("test 1") { fixture => val e = intercept[TestFailedException] { assert(a == 2) } assert(e.message == Some("1 did not equal 2")) assert(e.failedCodeFileName == Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber == Some(thisLineNumber - 4)) } registerTest("test 2") { fixture => assert(a == 2) } registerTest("test 3") { fixture => pending } registerTest("test 4") { fixture => cancel } registerIgnoredTest("test 5") { fixture => assert(a == 2) } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(rep.testStartingEventsReceived.length == 4) assert(rep.testSucceededEventsReceived.length == 1) assert(rep.testSucceededEventsReceived(0).testName == "test 1") assert(rep.testFailedEventsReceived.length == 1) assert(rep.testFailedEventsReceived(0).testName == "test 2") assert(rep.testPendingEventsReceived.length == 1) assert(rep.testPendingEventsReceived(0).testName == "test 3") assert(rep.testCanceledEventsReceived.length == 1) assert(rep.testCanceledEventsReceived(0).testName == "test 4") assert(rep.testIgnoredEventsReceived.length == 1) assert(rep.testIgnoredEventsReceived(0).testName == "test 5") } it("should generate TestRegistrationClosedException with correct stack depth info when has a registerTest nested inside a registerTest") { class TestSpec extends WordSpec { type FixtureParam = String var registrationClosedThrown = false "a feature" should { registerTest("a scenario") { fixture => registerTest("nested scenario") { fixture => } } } override def withFixture(test: OneArgTest): Outcome = { val outcome = test("test") outcome match { case Exceptional(ex: TestRegistrationClosedException) => registrationClosedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.registrationClosedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[TestRegistrationClosedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[TestRegistrationClosedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 24) assert(trce.message == Some("Test cannot be nested inside another test.")) } it("should generate TestRegistrationClosedException with correct stack depth info when has a registerIgnoredTest nested inside a registerTest") { class TestSpec extends WordSpec { type FixtureParam = String var registrationClosedThrown = false "a feature" should { registerTest("a scenario") { fixture => registerIgnoredTest("nested scenario") { fixture => } } } override def withFixture(test: OneArgTest): Outcome = { val outcome = test("test") outcome match { case Exceptional(ex: TestRegistrationClosedException) => registrationClosedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.registrationClosedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[TestRegistrationClosedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[TestRegistrationClosedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 24) assert(trce.message == Some("Test cannot be nested inside another test.")) } } } describe("when failure happens") { it("should fire TestFailed event with correct stack depth info when test failed") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" should { "chill out" in { fixture => assert(1 === 2) } } } val rep = new EventRecordingReporter val s1 = new TestSpec s1.run(None, Args(rep)) assert(rep.testFailedEventsReceived.size === 1) assert(rep.testFailedEventsReceived(0).throwable.get.asInstanceOf[TestFailedException].failedCodeFileName.get === "WordSpecSpec.scala") assert(rep.testFailedEventsReceived(0).throwable.get.asInstanceOf[TestFailedException].failedCodeLineNumber.get === thisLineNumber - 9) } it("should generate TestRegistrationClosedException with correct stack depth info when has an in nested inside an in") { class TestSpec extends WordSpec { type FixtureParam = String var registrationClosedThrown = false "a feature" should { "a scenario" in { fixture => "nested scenario" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: TestRegistrationClosedException) => registrationClosedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.registrationClosedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[TestRegistrationClosedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[TestRegistrationClosedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 24) assert(trce.message == Some("An in clause may not appear inside another in clause.")) } it("should generate TestRegistrationClosedException with correct stack depth info when has an ignore nested inside an in") { class TestSpec extends WordSpec { type FixtureParam = String var registrationClosedThrown = false "a feature" should { "a scenario" in { fixture => "nested scenario" ignore { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: TestRegistrationClosedException) => registrationClosedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.registrationClosedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[TestRegistrationClosedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[TestRegistrationClosedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 24) assert(trce.message == Some("An ignore clause may not appear inside an in clause.")) } } describe("shorthand syntax") { describe("'it'") { describe("under top level") { it("should work with subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } it should { "do something interesting 1" in { fixture => } } it can { "do something interesting 2" in { fixture => } } it must { "do something interesting 3" in { fixture => } } it when { "do something interesting 4" in { fixture => } } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) val testStartingList = rep.testStartingEventsReceived assert(testStartingList.size === 5) assert(testStartingList(0).testName === "A Stack when empty should be empty") assert(testStartingList(1).testName === "A Stack should do something interesting 1") assert(testStartingList(2).testName === "A Stack can do something interesting 2") assert(testStartingList(3).testName === "A Stack must do something interesting 3") assert(testStartingList(4).testName === "A Stack when do something interesting 4") val testSucceededList = rep.testSucceededEventsReceived assert(testSucceededList.size === 5) assert(testSucceededList(0).testName === "A Stack when empty should be empty") assert(testSucceededList(1).testName === "A Stack should do something interesting 1") assert(testSucceededList(2).testName === "A Stack can do something interesting 2") assert(testSucceededList(3).testName === "A Stack must do something interesting 3") assert(testSucceededList(4).testName === "A Stack when do something interesting 4") } it("should throw NotAllowedException with correct stack depth and message when 'it should' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } it should { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } it can { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } it must { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } it when { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it should' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } it should { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } it can { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } it must { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } it when { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } } describe("under inner level") { it("should throw NotAllowedException with correct stack depth and message when 'it should' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } it should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } it can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } it must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } it when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it should' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { it should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { it can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { it must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { it when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it should' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } it should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } it can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } it must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } it when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "An it clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } } describe("under 'in' clause") { it("should throw NotAllowedException with correct stack depth and message when 'it should' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => it should { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "An it clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'it can' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => it can { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "An it clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'it must' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => it must { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "An it clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'it when' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => it when { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "An it clause must only appear after a top level subject clause.") } } } describe("'they'") { describe("under top level") { it("should work with subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } they should { "do something interesting 1" in { fixture => } } they can { "do something interesting 2" in { fixture => } } they must { "do something interesting 3" in { fixture => } } they when { "do something interesting 4" in { fixture => } } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) val testStartingList = rep.testStartingEventsReceived assert(testStartingList.size === 5) assert(testStartingList(0).testName === "A Stack when empty should be empty") assert(testStartingList(1).testName === "A Stack should do something interesting 1") assert(testStartingList(2).testName === "A Stack can do something interesting 2") assert(testStartingList(3).testName === "A Stack must do something interesting 3") assert(testStartingList(4).testName === "A Stack when do something interesting 4") val testSucceededList = rep.testSucceededEventsReceived assert(testSucceededList.size === 5) assert(testSucceededList(0).testName === "A Stack when empty should be empty") assert(testSucceededList(1).testName === "A Stack should do something interesting 1") assert(testSucceededList(2).testName === "A Stack can do something interesting 2") assert(testSucceededList(3).testName === "A Stack must do something interesting 3") assert(testSucceededList(4).testName === "A Stack when do something interesting 4") } it("should throw NotAllowedException with correct stack depth and message when 'they should' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } they should { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } they can { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } they must { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called without subject") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } they when { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they should' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } they should { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } they can { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } they must { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } } "Other do something special" in { fixture => } they when { "do something interesting" in { fixture => } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 9)) } } describe("under inner level") { it("should throw NotAllowedException with correct stack depth and message when 'they should' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } they should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } they can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } they must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called with inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } they when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they should' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { they should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { they can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { they must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called without inner branch") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { they when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they should' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } they should { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } they can { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } they must { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called with inner branch but after an 'in' clause") { class TestSpec extends WordSpec { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } "A Stack" when { "empty" should { "be empty" in { fixture => } } "do something" in { fixture => } they when { "do something interesting" in { fixture => } } } } val e = intercept[exceptions.NotAllowedException] { new TestSpec } assert(e.getMessage === "A they clause must only appear after a top level subject clause.") assert(e.failedCodeFileName === Some("WordSpecSpec.scala")) assert(e.failedCodeLineNumber === Some(thisLineNumber - 10)) } } describe("under 'in' clause") { it("should throw NotAllowedException with correct stack depth and message when 'they should' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => they should { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "A they clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'they can' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => they can { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "A they clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'they must' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => they must { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "A they clause must only appear after a top level subject clause.") } it("should throw NotAllowedException with correct stack depth and message when 'they when' is called") { class TestSpec extends WordSpec { type FixtureParam = String var notAllowedThrown = false "Something special" in { fixture => they when { "do something interesting" in { fixture => } } } def withFixture(test: OneArgTest): Outcome = { val outcome = test.apply("hi") outcome match { case Exceptional(ex: exceptions.NotAllowedException) => notAllowedThrown = true case _ => } outcome } } val rep = new EventRecordingReporter val s = new TestSpec s.run(None, Args(rep)) assert(s.notAllowedThrown == true) val testFailedEvents = rep.testFailedEventsReceived assert(testFailedEvents.size === 1) assert(testFailedEvents(0).throwable.get.getClass() === classOf[exceptions.NotAllowedException]) val trce = testFailedEvents(0).throwable.get.asInstanceOf[exceptions.NotAllowedException] assert("WordSpecSpec.scala" === trce.failedCodeFileName.get) assert(trce.failedCodeLineNumber.get === thisLineNumber - 23) assert(trce.getMessage === "A they clause must only appear after a top level subject clause.") } } } } }
travisbrown/scalatest
src/test/scala/org/scalatest/fixture/WordSpecSpec.scala
Scala
apache-2.0
126,066
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.test import org.apache.spark.sql.{DataFrame, SparkSession, SQLContext} import org.apache.carbondata.common.logging.LogServiceFactory import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.util.CarbonProperties /** * This class is a sql executor of unit test case for spark version 2.x. */ class Spark2TestQueryExecutor extends TestQueryExecutorRegister { override def sql(sqlText: String): DataFrame = Spark2TestQueryExecutor.spark.sql(sqlText) override def sqlContext: SQLContext = Spark2TestQueryExecutor.spark.sqlContext } object Spark2TestQueryExecutor { private val LOGGER = LogServiceFactory.getLogService(this.getClass.getCanonicalName) LOGGER.info("use TestQueryExecutorImplV2") CarbonProperties.getInstance() .addProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, TestQueryExecutor.timestampFormat) .addProperty(CarbonCommonConstants.STORE_LOCATION_TEMP_PATH, System.getProperty("java.io.tmpdir")) .addProperty(CarbonCommonConstants.LOCK_TYPE, CarbonCommonConstants.CARBON_LOCK_TYPE_LOCAL) .addProperty(CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION, "FORCE") import org.apache.spark.sql.CarbonSession._ val spark = SparkSession .builder() .master("local[2]") .appName("Spark2TestQueryExecutor") .enableHiveSupport() .config("spark.sql.warehouse.dir", TestQueryExecutor.warehouse) .getOrCreateCarbonSession(TestQueryExecutor.storeLocation, TestQueryExecutor.metastoredb) spark.sparkContext.setLogLevel("ERROR") }
Sephiroth-Lin/incubator-carbondata
integration/spark2/src/main/scala/org/apache/spark/sql/test/Spark2TestQueryExecutor.scala
Scala
apache-2.0
2,378
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.mllib.linalg import com.github.fommil.netlib.{BLAS => NetlibBLAS, F2jBLAS} import com.github.fommil.netlib.BLAS.{getInstance => NativeBLAS} import org.apache.spark.Logging /** * BLAS routines for MLlib's vectors and matrices. */ private[spark] object BLAS extends Serializable with Logging { @transient private var _f2jBLAS: NetlibBLAS = _ @transient private var _nativeBLAS: NetlibBLAS = _ // For level-1 routines, we use Java implementation. private def f2jBLAS: NetlibBLAS = { if (_f2jBLAS == null) { _f2jBLAS = new F2jBLAS } _f2jBLAS } /** * y += a * x */ def axpy(a: Double, x: Vector, y: Vector): Unit = { require(x.size == y.size) y match { case dy: DenseVector => x match { case sx: SparseVector => axpy(a, sx, dy) case dx: DenseVector => axpy(a, dx, dy) case _ => throw new UnsupportedOperationException( s"axpy doesn't support x type ${x.getClass}.") } case _ => throw new IllegalArgumentException( s"axpy only supports adding to a dense vector but got type ${y.getClass}.") } } /** * y += a * x */ private def axpy(a: Double, x: DenseVector, y: DenseVector): Unit = { val n = x.size f2jBLAS.daxpy(n, a, x.values, 1, y.values, 1) } /** * y += a * x */ private def axpy(a: Double, x: SparseVector, y: DenseVector): Unit = { val xValues = x.values val xIndices = x.indices val yValues = y.values val nnz = xIndices.size if (a == 1.0) { var k = 0 while (k < nnz) { yValues(xIndices(k)) += xValues(k) k += 1 } } else { var k = 0 while (k < nnz) { yValues(xIndices(k)) += a * xValues(k) k += 1 } } } /** * dot(x, y) */ def dot(x: Vector, y: Vector): Double = { require(x.size == y.size, "BLAS.dot(x: Vector, y:Vector) was given Vectors with non-matching sizes:" + " x.size = " + x.size + ", y.size = " + y.size) (x, y) match { case (dx: DenseVector, dy: DenseVector) => dot(dx, dy) case (sx: SparseVector, dy: DenseVector) => dot(sx, dy) case (dx: DenseVector, sy: SparseVector) => dot(sy, dx) case (sx: SparseVector, sy: SparseVector) => dot(sx, sy) case _ => throw new IllegalArgumentException(s"dot doesn't support (${x.getClass}, ${y.getClass}).") } } /** * dot(x, y) */ private def dot(x: DenseVector, y: DenseVector): Double = { val n = x.size f2jBLAS.ddot(n, x.values, 1, y.values, 1) } /** * dot(x, y) */ private def dot(x: SparseVector, y: DenseVector): Double = { val xValues = x.values val xIndices = x.indices val yValues = y.values val nnz = xIndices.size var sum = 0.0 var k = 0 while (k < nnz) { sum += xValues(k) * yValues(xIndices(k)) k += 1 } sum } /** * dot(x, y) */ private def dot(x: SparseVector, y: SparseVector): Double = { val xValues = x.values val xIndices = x.indices val yValues = y.values val yIndices = y.indices val nnzx = xIndices.size val nnzy = yIndices.size var kx = 0 var ky = 0 var sum = 0.0 // y catching x while (kx < nnzx && ky < nnzy) { val ix = xIndices(kx) while (ky < nnzy && yIndices(ky) < ix) { ky += 1 } if (ky < nnzy && yIndices(ky) == ix) { sum += xValues(kx) * yValues(ky) ky += 1 } kx += 1 } sum } /** * y = x */ def copy(x: Vector, y: Vector): Unit = { val n = y.size require(x.size == n) y match { case dy: DenseVector => x match { case sx: SparseVector => val sxIndices = sx.indices val sxValues = sx.values val dyValues = dy.values val nnz = sxIndices.size var i = 0 var k = 0 while (k < nnz) { val j = sxIndices(k) while (i < j) { dyValues(i) = 0.0 i += 1 } dyValues(i) = sxValues(k) i += 1 k += 1 } while (i < n) { dyValues(i) = 0.0 i += 1 } case dx: DenseVector => Array.copy(dx.values, 0, dy.values, 0, n) } case _ => throw new IllegalArgumentException(s"y must be dense in copy but got ${y.getClass}") } } /** * x = a * x */ def scal(a: Double, x: Vector): Unit = { x match { case sx: SparseVector => f2jBLAS.dscal(sx.values.length, a, sx.values, 1) case dx: DenseVector => f2jBLAS.dscal(dx.values.length, a, dx.values, 1) case _ => throw new IllegalArgumentException(s"scal doesn't support vector type ${x.getClass}.") } } // For level-3 routines, we use the native BLAS. private def nativeBLAS: NetlibBLAS = { if (_nativeBLAS == null) { _nativeBLAS = NativeBLAS } _nativeBLAS } /** * A := alpha * x * x^T^ + A * @param alpha a real scalar that will be multiplied to x * x^T^. * @param x the vector x that contains the n elements. * @param A the symmetric matrix A. Size of n x n. */ def syr(alpha: Double, x: Vector, A: DenseMatrix) { val mA = A.numRows val nA = A.numCols require(mA == nA, s"A is not a square matrix (and hence is not symmetric). A: $mA x $nA") require(mA == x.size, s"The size of x doesn't match the rank of A. A: $mA x $nA, x: ${x.size}") x match { case dv: DenseVector => syr(alpha, dv, A) case sv: SparseVector => syr(alpha, sv, A) case _ => throw new IllegalArgumentException(s"syr doesn't support vector type ${x.getClass}.") } } private def syr(alpha: Double, x: DenseVector, A: DenseMatrix) { val nA = A.numRows val mA = A.numCols nativeBLAS.dsyr("U", x.size, alpha, x.values, 1, A.values, nA) // Fill lower triangular part of A var i = 0 while (i < mA) { var j = i + 1 while (j < nA) { A(j, i) = A(i, j) j += 1 } i += 1 } } private def syr(alpha: Double, x: SparseVector, A: DenseMatrix) { val mA = A.numCols val xIndices = x.indices val xValues = x.values val nnz = xValues.length val Avalues = A.values var i = 0 while (i < nnz) { val multiplier = alpha * xValues(i) val offset = xIndices(i) * mA var j = 0 while (j < nnz) { Avalues(xIndices(j) + offset) += multiplier * xValues(j) j += 1 } i += 1 } } /** * C := alpha * A * B + beta * C * @param alpha a scalar to scale the multiplication A * B. * @param A the matrix A that will be left multiplied to B. Size of m x k. * @param B the matrix B that will be left multiplied by A. Size of k x n. * @param beta a scalar that can be used to scale matrix C. * @param C the resulting matrix C. Size of m x n. C.isTransposed must be false. */ def gemm( alpha: Double, A: Matrix, B: DenseMatrix, beta: Double, C: DenseMatrix): Unit = { require(!C.isTransposed, "The matrix C cannot be the product of a transpose() call. C.isTransposed must be false.") if (alpha == 0.0 && beta == 1.0) { logDebug("gemm: alpha is equal to 0 and beta is equal to 1. Returning C.") } else if (alpha == 0.0) { f2jBLAS.dscal(C.values.length, beta, C.values, 1) } else { A match { case sparse: SparseMatrix => gemm(alpha, sparse, B, beta, C) case dense: DenseMatrix => gemm(alpha, dense, B, beta, C) case _ => throw new IllegalArgumentException(s"gemm doesn't support matrix type ${A.getClass}.") } } } /** * C := alpha * A * B + beta * C * For `DenseMatrix` A. */ private def gemm( alpha: Double, A: DenseMatrix, B: DenseMatrix, beta: Double, C: DenseMatrix): Unit = { val tAstr = if (A.isTransposed) "T" else "N" val tBstr = if (B.isTransposed) "T" else "N" val lda = if (!A.isTransposed) A.numRows else A.numCols val ldb = if (!B.isTransposed) B.numRows else B.numCols require(A.numCols == B.numRows, s"The columns of A don't match the rows of B. A: ${A.numCols}, B: ${B.numRows}") require(A.numRows == C.numRows, s"The rows of C don't match the rows of A. C: ${C.numRows}, A: ${A.numRows}") require(B.numCols == C.numCols, s"The columns of C don't match the columns of B. C: ${C.numCols}, A: ${B.numCols}") nativeBLAS.dgemm(tAstr, tBstr, A.numRows, B.numCols, A.numCols, alpha, A.values, lda, B.values, ldb, beta, C.values, C.numRows) } /** * C := alpha * A * B + beta * C * For `SparseMatrix` A. */ private def gemm( alpha: Double, A: SparseMatrix, B: DenseMatrix, beta: Double, C: DenseMatrix): Unit = { val mA: Int = A.numRows val nB: Int = B.numCols val kA: Int = A.numCols val kB: Int = B.numRows require(kA == kB, s"The columns of A don't match the rows of B. A: $kA, B: $kB") require(mA == C.numRows, s"The rows of C don't match the rows of A. C: ${C.numRows}, A: $mA") require(nB == C.numCols, s"The columns of C don't match the columns of B. C: ${C.numCols}, A: $nB") val Avals = A.values val Bvals = B.values val Cvals = C.values val ArowIndices = A.rowIndices val AcolPtrs = A.colPtrs // Slicing is easy in this case. This is the optimal multiplication setting for sparse matrices if (A.isTransposed){ var colCounterForB = 0 if (!B.isTransposed) { // Expensive to put the check inside the loop while (colCounterForB < nB) { var rowCounterForA = 0 val Cstart = colCounterForB * mA val Bstart = colCounterForB * kA while (rowCounterForA < mA) { var i = AcolPtrs(rowCounterForA) val indEnd = AcolPtrs(rowCounterForA + 1) var sum = 0.0 while (i < indEnd) { sum += Avals(i) * Bvals(Bstart + ArowIndices(i)) i += 1 } val Cindex = Cstart + rowCounterForA Cvals(Cindex) = beta * Cvals(Cindex) + sum * alpha rowCounterForA += 1 } colCounterForB += 1 } } else { while (colCounterForB < nB) { var rowCounterForA = 0 val Cstart = colCounterForB * mA while (rowCounterForA < mA) { var i = AcolPtrs(rowCounterForA) val indEnd = AcolPtrs(rowCounterForA + 1) var sum = 0.0 while (i < indEnd) { sum += Avals(i) * B(ArowIndices(i), colCounterForB) i += 1 } val Cindex = Cstart + rowCounterForA Cvals(Cindex) = beta * Cvals(Cindex) + sum * alpha rowCounterForA += 1 } colCounterForB += 1 } } } else { // Scale matrix first if `beta` is not equal to 1.0 if (beta != 1.0) { f2jBLAS.dscal(C.values.length, beta, C.values, 1) } // Perform matrix multiplication and add to C. The rows of A are multiplied by the columns of // B, and added to C. var colCounterForB = 0 // the column to be updated in C if (!B.isTransposed) { // Expensive to put the check inside the loop while (colCounterForB < nB) { var colCounterForA = 0 // The column of A to multiply with the row of B val Bstart = colCounterForB * kB val Cstart = colCounterForB * mA while (colCounterForA < kA) { var i = AcolPtrs(colCounterForA) val indEnd = AcolPtrs(colCounterForA + 1) val Bval = Bvals(Bstart + colCounterForA) * alpha while (i < indEnd) { Cvals(Cstart + ArowIndices(i)) += Avals(i) * Bval i += 1 } colCounterForA += 1 } colCounterForB += 1 } } else { while (colCounterForB < nB) { var colCounterForA = 0 // The column of A to multiply with the row of B val Cstart = colCounterForB * mA while (colCounterForA < kA) { var i = AcolPtrs(colCounterForA) val indEnd = AcolPtrs(colCounterForA + 1) val Bval = B(colCounterForA, colCounterForB) * alpha while (i < indEnd) { Cvals(Cstart + ArowIndices(i)) += Avals(i) * Bval i += 1 } colCounterForA += 1 } colCounterForB += 1 } } } } /** * y := alpha * A * x + beta * y * @param alpha a scalar to scale the multiplication A * x. * @param A the matrix A that will be left multiplied to x. Size of m x n. * @param x the vector x that will be left multiplied by A. Size of n x 1. * @param beta a scalar that can be used to scale vector y. * @param y the resulting vector y. Size of m x 1. */ def gemv( alpha: Double, A: Matrix, x: Vector, beta: Double, y: DenseVector): Unit = { require(A.numCols == x.size, s"The columns of A don't match the number of elements of x. A: ${A.numCols}, x: ${x.size}") require(A.numRows == y.size, s"The rows of A don't match the number of elements of y. A: ${A.numRows}, y:${y.size}") if (alpha == 0.0 && beta == 1.0) { logDebug("gemv: alpha is equal to 0 and beta is equal to 1. Returning y.") } else if (alpha == 0.0) { scal(beta, y) } else { (A, x) match { case (smA: SparseMatrix, dvx: DenseVector) => gemv(alpha, smA, dvx, beta, y) case (smA: SparseMatrix, svx: SparseVector) => gemv(alpha, smA, svx, beta, y) case (dmA: DenseMatrix, dvx: DenseVector) => gemv(alpha, dmA, dvx, beta, y) case (dmA: DenseMatrix, svx: SparseVector) => gemv(alpha, dmA, svx, beta, y) case _ => throw new IllegalArgumentException(s"gemv doesn't support running on matrix type " + s"${A.getClass} and vector type ${x.getClass}.") } } } /** * y := alpha * A * x + beta * y * For `DenseMatrix` A and `DenseVector` x. */ private def gemv( alpha: Double, A: DenseMatrix, x: DenseVector, beta: Double, y: DenseVector): Unit = { val tStrA = if (A.isTransposed) "T" else "N" val mA = if (!A.isTransposed) A.numRows else A.numCols val nA = if (!A.isTransposed) A.numCols else A.numRows nativeBLAS.dgemv(tStrA, mA, nA, alpha, A.values, mA, x.values, 1, beta, y.values, 1) } /** * y := alpha * A * x + beta * y * For `DenseMatrix` A and `SparseVector` x. */ private def gemv( alpha: Double, A: DenseMatrix, x: SparseVector, beta: Double, y: DenseVector): Unit = { val mA: Int = A.numRows val nA: Int = A.numCols val Avals = A.values val xIndices = x.indices val xNnz = xIndices.length val xValues = x.values val yValues = y.values if (A.isTransposed) { var rowCounterForA = 0 while (rowCounterForA < mA) { var sum = 0.0 var k = 0 while (k < xNnz) { sum += xValues(k) * Avals(xIndices(k) + rowCounterForA * nA) k += 1 } yValues(rowCounterForA) = sum * alpha + beta * yValues(rowCounterForA) rowCounterForA += 1 } } else { var rowCounterForA = 0 while (rowCounterForA < mA) { var sum = 0.0 var k = 0 while (k < xNnz) { sum += xValues(k) * Avals(xIndices(k) * mA + rowCounterForA) k += 1 } yValues(rowCounterForA) = sum * alpha + beta * yValues(rowCounterForA) rowCounterForA += 1 } } } /** * y := alpha * A * x + beta * y * For `SparseMatrix` A and `SparseVector` x. */ private def gemv( alpha: Double, A: SparseMatrix, x: SparseVector, beta: Double, y: DenseVector): Unit = { val xValues = x.values val xIndices = x.indices val xNnz = xIndices.length val yValues = y.values val mA: Int = A.numRows val nA: Int = A.numCols val Avals = A.values val Arows = if (!A.isTransposed) A.rowIndices else A.colPtrs val Acols = if (!A.isTransposed) A.colPtrs else A.rowIndices if (A.isTransposed) { var rowCounter = 0 while (rowCounter < mA) { var i = Arows(rowCounter) val indEnd = Arows(rowCounter + 1) var sum = 0.0 var k = 0 while (k < xNnz && i < indEnd) { if (xIndices(k) == Acols(i)) { sum += Avals(i) * xValues(k) i += 1 } k += 1 } yValues(rowCounter) = sum * alpha + beta * yValues(rowCounter) rowCounter += 1 } } else { if (beta != 1.0) scal(beta, y) var colCounterForA = 0 var k = 0 while (colCounterForA < nA && k < xNnz) { if (xIndices(k) == colCounterForA) { var i = Acols(colCounterForA) val indEnd = Acols(colCounterForA + 1) val xTemp = xValues(k) * alpha while (i < indEnd) { val rowIndex = Arows(i) yValues(Arows(i)) += Avals(i) * xTemp i += 1 } k += 1 } colCounterForA += 1 } } } /** * y := alpha * A * x + beta * y * For `SparseMatrix` A and `DenseVector` x. */ private def gemv( alpha: Double, A: SparseMatrix, x: DenseVector, beta: Double, y: DenseVector): Unit = { val xValues = x.values val yValues = y.values val mA: Int = A.numRows val nA: Int = A.numCols val Avals = A.values val Arows = if (!A.isTransposed) A.rowIndices else A.colPtrs val Acols = if (!A.isTransposed) A.colPtrs else A.rowIndices // Slicing is easy in this case. This is the optimal multiplication setting for sparse matrices if (A.isTransposed) { var rowCounter = 0 while (rowCounter < mA) { var i = Arows(rowCounter) val indEnd = Arows(rowCounter + 1) var sum = 0.0 while (i < indEnd) { sum += Avals(i) * xValues(Acols(i)) i += 1 } yValues(rowCounter) = beta * yValues(rowCounter) + sum * alpha rowCounter += 1 } } else { if (beta != 1.0) scal(beta, y) // Perform matrix-vector multiplication and add to y var colCounterForA = 0 while (colCounterForA < nA) { var i = Acols(colCounterForA) val indEnd = Acols(colCounterForA + 1) val xVal = xValues(colCounterForA) * alpha while (i < indEnd) { val rowIndex = Arows(i) yValues(rowIndex) += Avals(i) * xVal i += 1 } colCounterForA += 1 } } } }
tophua/spark1.52
mllib/src/main/scala/org/apache/spark/mllib/linalg/BLAS.scala
Scala
apache-2.0
19,857
package ch.ethz.inf.da.tipstersearch.scoring /** * Abstract class representing a basic relevance model. * It provdides access to useful functions. */ abstract class RelevanceModel { /** * Override this function to compute the score of given document and given query * * @param queryTokens the list of tokens in the query * @param documentTokens the list of tokens in the document * @return the document's score for this query */ def score(queryTokens:List[String], documentTokens:List[String]) : Double /** * Computes the log_2 * * @param x the value to compute the log2 for */ def log2(x: Double) = scala.math.log(x)/scala.math.log(2) /** * Computes the term frequencies of given tokens * * @param tokens the tokens to compute the frequencies for */ def tf(tokens:List[String]) : Map[String, Int] = tokens.groupBy(identity).mapValues(l => l.length) }
rjagerman/TipsterSearch
src/main/scala/scoring/RelevanceModel.scala
Scala
mit
1,006
package io.ubiqesh.uplink.disruptor.persistence.actions import io.ubiqesh.uplink.vertx.event.StateChangeEvent import io.ubiqesh.uplink.vertx.json.Node import io.ubiqesh.uplink.persistence.Persistence import org.vertx.java.core.json.JsonObject class UpdateAction(private var persistence: Persistence) { def handle(event: StateChangeEvent) { val path = event.extractNodePath() var payload: JsonObject = null if (event.getFieldNames.contains(StateChangeEvent.PAYLOAD)) { val obj = event.getField(StateChangeEvent.PAYLOAD) if (obj.isInstanceOf[JsonObject]) { payload = obj.asInstanceOf[JsonObject] if (payload.isInstanceOf[JsonObject]) { persistence.updateValue(event.getChangeLog, path, obj) } } } else { persistence.remove(event.getChangeLog, path) } } }
ubiqesh/ubiqesh
uplink/src/main/scala/io/ubiqesh/uplink/disruptor/persistence/actions/UpdateAction.scala
Scala
apache-2.0
838
import sbt._ //Taken from the xsbt sbt project. (that is, the build config used by the sbt source itself) //I have modified this, of course. trait Sxr extends BasicScalaProject { val sxrConf = config("sxr") hide val sxrDep = "org.scala-tools.sxr" %% "sxr" % "[0.2.7,)" % sxrConf.name jar() def deepSources: PathFinder = mainScalaSourcePath ** GlobFilter("*.scala") //** means "find -R all files matching" def mainScalaSourcePath: Path //def deepBaseDirectories: PathFinder def sxrBaseDirs = "-P:sxr:base-directory:" + mainScalaSourcePath.absolutePath //deepBaseDirectories.absString def sxrLocation = "-Xplugin:" + managedClasspath(sxrConf).absString def sxrDirName = "browse" def sxrOutput = outputPath / (sxrDirName + ".sxr") def sxrClassesOutput = outputPath / sxrDirName // isn't actually written to, since compiler stops before writing classes def sxrOptions = compileOptions.map(_.asString) ++ Seq(sxrBaseDirs, sxrLocation) lazy val sxr = task { xsbt.FileUtilities.delete(sxrOutput +++ sxrClassesOutput getFiles) xsbt.FileUtilities.createDirectory(sxrClassesOutput asFile) val compiler = new xsbt.RawCompiler(buildScalaInstance, xsbt.ClasspathOptions.auto, log) compiler(deepSources.getFiles, compileClasspath.getFiles, sxrClassesOutput asFile, sxrOptions) None } }
thomasmodeneis/jgo
src/project/build/Sxr.scala
Scala
gpl-3.0
1,326
/* Copyright 2009-2018 EPFL, Lausanne */ package inox package transformers trait Transformer { val s: ast.Trees val t: ast.Trees type Env lazy val deconstructor: ast.TreeDeconstructor { val s: Transformer.this.s.type val t: Transformer.this.t.type } = s.getDeconstructor(t) def transform(id: Identifier, env: Env): Identifier = id def transform(id: Identifier, tpe: s.Type, env: Env): (Identifier, t.Type) = { (transform(id, env), transform(tpe, env)) } def transform(vd: s.ValDef, env: Env): t.ValDef = { val s.ValDef(id, tpe, flags) = vd val (newId, newTpe) = transform(id, tpe, env) var changed = false val newFlags = for (f <- flags) yield { val newFlag = transform(f, env) if (f ne newFlag) changed = true newFlag } if ((id ne newId) || (tpe ne newTpe) || changed || (s ne t)) { t.ValDef(newId, newTpe, newFlags).copiedFrom(vd) } else { vd.asInstanceOf[t.ValDef] } } def transform(tpd: s.TypeParameterDef, env: Env): t.TypeParameterDef = { val newTp = transform(tpd.tp, env) if ((tpd.tp ne newTp) || (s ne t)) { t.TypeParameterDef(newTp.asInstanceOf[t.TypeParameter]) } else { tpd.asInstanceOf[t.TypeParameterDef] } } def transform(e: s.Expr, env: Env): t.Expr = { val (ids, vs, es, tps, flags, builder) = deconstructor.deconstruct(e) var changed = false val newIds = for (id <- ids) yield { val newId = transform(id, env) if (id ne newId) changed = true newId } val newVs = for (v <- vs) yield { val vd = v.toVal val newVd = transform(vd, env) if (vd ne newVd) changed = true newVd.toVariable } val newEs = for (e <- es) yield { val newE = transform(e, env) if (e ne newE) changed = true newE } val newTps = for (tp <- tps) yield { val newTp = transform(tp, env) if (tp ne newTp) changed = true newTp } val newFlags = for (flag <- flags) yield { val newFlag = transform(flag, env) if (flag ne newFlag) changed = true newFlag } if (changed || (s ne t)) { builder(newIds, newVs, newEs, newTps, newFlags).copiedFrom(e) } else { e.asInstanceOf[t.Expr] } } def transform(tpe: s.Type, env: Env): t.Type = { val (ids, vs, es, tps, flags, builder) = deconstructor.deconstruct(tpe) var changed = false val newIds = for (id <- ids) yield { val newId = transform(id, env) if (id ne newId) changed = true newId } val newVs = for (v <- vs) yield { val vd = v.toVal val newVd = transform(vd, env) if (vd ne newVd) changed = true newVd.toVariable } val newEs = for (e <- es) yield { val newE = transform(e, env) if (e ne newE) changed = true newE } val newTps = for (tp <- tps) yield { val newTp = transform(tp, env) if (tp ne newTp) changed = true newTp } val newFlags = for (f <- flags) yield { val newFlag = transform(f, env) if (f ne newFlag) changed = true newFlag } val res = if (changed || (s ne t)) { builder(newIds, newVs, newEs, newTps, newFlags).copiedFrom(tpe) } else { tpe.asInstanceOf[t.Type] } res } def transform(flag: s.Flag, env: Env): t.Flag = { val (ids, es, tps, builder) = deconstructor.deconstruct(flag) var changed = false val newIds = for (id <- ids) yield { val newId = transform(id, env) if (id ne newId) changed = true newId } val newEs = for (e <- es) yield { val newE = transform(e, env) if (e ne newE) changed = true newE } val newTps = for (tp <- tps) yield { val newTp = transform(tp, env) if (tp ne newTp) changed = true newTp } if (changed || (s ne t)) { builder(newIds, newEs, newTps) } else { flag.asInstanceOf[t.Flag] } } } trait DefinitionTransformer extends Transformer { def initEnv: Env def transform(fd: s.FunDef): t.FunDef = { val env = initEnv new t.FunDef( transform(fd.id, env), fd.tparams map (transform(_, env)), fd.params map (transform(_, env)), transform(fd.returnType, env), transform(fd.fullBody, env), fd.flags map (transform(_, env)) ).copiedFrom(fd) } def transform(sort: s.ADTSort): t.ADTSort = { val env = initEnv new t.ADTSort( transform(sort.id, env), sort.tparams map (transform(_, env)), sort.constructors map { cons => new t.ADTConstructor( transform(cons.id, env), transform(cons.sort, env), cons.fields map (transform(_, env)) ).copiedFrom(cons) }, sort.flags map (transform(_, env)) ).copiedFrom(sort) } } trait TreeTransformer extends DefinitionTransformer { override final type Env = Unit override final val initEnv: Unit = () def transform(id: Identifier): Identifier = super.transform(id, ()) override final def transform(id: Identifier, env: Env): Identifier = transform(id) def transform(id: Identifier, tpe: s.Type): (Identifier, t.Type) = super.transform(id, tpe, ()) override final def transform(id: Identifier, tpe: s.Type, env: Env): (Identifier, t.Type) = transform(id, tpe) def transform(vd: s.ValDef): t.ValDef = super.transform(vd, ()) override final def transform(vd: s.ValDef, env: Env): t.ValDef = transform(vd) def transform(tpd: s.TypeParameterDef): t.TypeParameterDef = super.transform(tpd, ()) override final def transform(tpd: s.TypeParameterDef, env: Env): t.TypeParameterDef = transform(tpd) def transform(e: s.Expr): t.Expr = super.transform(e, ()) override final def transform(e: s.Expr, env: Env): t.Expr = transform(e) def transform(tpe: s.Type): t.Type = super.transform(tpe, ()) override final def transform(tpe: s.Type, env: Env): t.Type = transform(tpe) def transform(flag: s.Flag): t.Flag = super.transform(flag, ()) override final def transform(flag: s.Flag, env: Env): t.Flag = transform(flag) protected trait TreeTransformerComposition extends TreeTransformer { protected val t1: TreeTransformer protected val t2: TreeTransformer { val s: t1.t.type } final lazy val s: t1.s.type = t1.s final lazy val t: t2.t.type = t2.t override final def transform(id: Identifier): Identifier = t2.transform(t1.transform(id)) override final def transform(id: Identifier, tpe: s.Type): (Identifier, t.Type) = { val (id1, tp1) = t1.transform(id, tpe) t2.transform(id1, tp1) } override final def transform(vd: s.ValDef): t.ValDef = t2.transform(t1.transform(vd)) override final def transform(e: s.Expr): t.Expr = t2.transform(t1.transform(e)) override final def transform(tpe: s.Type): t.Type = t2.transform(t1.transform(tpe)) override final def transform(flag: s.Flag): t.Flag = t2.transform(t1.transform(flag)) override final def transform(fd: s.FunDef): t.FunDef = t2.transform(t1.transform(fd)) override final def transform(sort: s.ADTSort): t.ADTSort = t2.transform(t1.transform(sort)) } def compose(that: TreeTransformer { val t: TreeTransformer.this.s.type }): TreeTransformer { val s: that.s.type val t: TreeTransformer.this.t.type } = { // the scala type checker doesn't realize that this relation must hold here that andThen this.asInstanceOf[TreeTransformer { val s: that.t.type val t: TreeTransformer.this.t.type }] } def andThen(that: TreeTransformer { val s: TreeTransformer.this.t.type }): TreeTransformer { val s: TreeTransformer.this.s.type val t: that.t.type } = new TreeTransformerComposition { val t1: TreeTransformer.this.type = TreeTransformer.this val t2: that.type = that } }
romac/inox
src/main/scala/inox/transformers/Transformer.scala
Scala
apache-2.0
7,830
package io.flow.delta.actors import akka.actor.{Actor, ActorSystem} import db._ import io.flow.akka.SafeReceive import io.flow.delta.api.lib.EventLogProcessor import io.flow.delta.v0.models.{Build, StateForm} import io.flow.log.RollbarLogger import k8s.KubernetesService import k8s.KubernetesService.toDeploymentName import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} object K8sBuildActor { trait Factory { def apply(buildId: String): Actor } } class K8sBuildActor @javax.inject.Inject() ( override val buildsDao: BuildsDao, override val configsDao: ConfigsDao, override val projectsDao: ProjectsDao, override val organizationsDao: OrganizationsDao, kubernetesService: KubernetesService, buildLastStatesDao: InternalBuildLastStatesDao, usersDao: UsersDao, system: ActorSystem, eventLogProcessor: EventLogProcessor, override val logger: RollbarLogger, @com.google.inject.assistedinject.Assisted buildId: String ) extends Actor with DataBuild { private[this] implicit val ec = system.dispatchers.lookup("build-actor-context") private[this] implicit val configuredRollbar = logger .fingerprint("K8sBuildActor") .withKeyValue("build_id", buildId) configuredRollbar.info(s"K8sBuildActor created for build[$buildId]") def receive = SafeReceive.withLogUnhandled { case BuildActor.Messages.Setup => configuredRollbar.info(s"K8sBuildActor BuildActor.Messages.Setup for build[${buildId}]") handleReceiveSetupEvent() case BuildActor.Messages.CheckLastState => configuredRollbar.info(s"K8sBuildActor BuildActor.Messages.CheckLastState for build[${buildId}]") withEnabledBuild { build => eventLogProcessor.runSync("CheckLastState", log = log(build.project.id)) { configuredRollbar.info(s"K8sBuildActor BuildActor.Messages.CheckLastState for build[${buildId}] with enabled build") captureLastState(build) } } } private[this] def handleReceiveSetupEvent(): Unit = { setBuildId(buildId) system.scheduler.scheduleWithFixedDelay( Duration(1L, "second"), Duration(EcsBuildActor.CheckLastStateIntervalSeconds, "seconds") ) { () => self ! BuildActor.Messages.CheckLastState } () } private[this] def captureLastState(build: Build): Unit = { Try { val deploymentName = toDeploymentName(build) configuredRollbar .withKeyValue("build_name", build.name) .withKeyValue("build_project_id", build.project.id) .withKeyValue("deploymentName", deploymentName) .info("CaptureLastState") kubernetesService.getDeployedVersions(deploymentName) } match { case Success(versions) => { buildLastStatesDao.upsert( usersDao.systemUser, build, StateForm(versions = versions) ) () } case Failure(ex) => { log(build).warn("Error getting deployed versions from k8s", ex) } } } private[this] def log(build: Build): RollbarLogger = { logger .organization(build.project.organization.id) .withKeyValue("project_id", build.project.id) .withKeyValue("build_name", build.name) } }
flowcommerce/delta
api/app/actors/K8sBuildActor.scala
Scala
mit
3,211
package mesosphere.marathon package core.task.jobs import akka.actor.{ ActorRef, PoisonPill, Terminated } import akka.event.LoggingAdapter import akka.testkit.TestProbe import mesosphere.AkkaUnitTest import mesosphere.marathon.core.base.{ Clock, ConstantClock } import mesosphere.marathon.core.condition.Condition import mesosphere.marathon.core.instance.{ Instance, TestInstanceBuilder } import mesosphere.marathon.core.instance.update.InstanceUpdateOperation import mesosphere.marathon.core.task.jobs.impl.{ ExpungeOverdueLostTasksActor, ExpungeOverdueLostTasksActorLogic } import mesosphere.marathon.core.task.tracker.InstanceTracker.InstancesBySpec import mesosphere.marathon.core.task.tracker.{ InstanceTracker, TaskStateOpProcessor } import mesosphere.marathon.state.PathId._ import mesosphere.marathon.state.{ Timestamp, UnreachableEnabled, UnreachableDisabled, UnreachableStrategy } import mesosphere.marathon.test.MarathonTestHelper import org.scalatest.prop.TableDrivenPropertyChecks import scala.concurrent.{ ExecutionContext, Future } import scala.concurrent.duration._ class ExpungeOverdueLostTasksActorTest extends AkkaUnitTest with TableDrivenPropertyChecks { class Fixture { val clock = ConstantClock() val config = MarathonTestHelper.defaultConfig(maxTasksPerOffer = 10) val stateOpProcessor: TaskStateOpProcessor = mock[TaskStateOpProcessor] val taskTracker: InstanceTracker = mock[InstanceTracker] val fiveTen = UnreachableEnabled(inactiveAfter = 5.minutes, expungeAfter = 10.minutes) } def withActor(testCode: (Fixture, ActorRef) => Any): Unit = { val f = new Fixture val checkActor = system.actorOf(ExpungeOverdueLostTasksActor.props(f.clock, f.config, f.taskTracker, f.stateOpProcessor)) try { testCode(f, checkActor) } finally { checkActor ! PoisonPill val probe = TestProbe() probe.watch(checkActor) val terminated = probe.expectMsgAnyClassOf(classOf[Terminated]) assert(terminated.actor == checkActor) } } "The expunge overdue tasks business logic's filtering methods" in { val f = new Fixture val businessLogic = new ExpungeOverdueLostTasksActorLogic { override val config: TaskJobsConfig = MarathonTestHelper.defaultConfig(maxTasksPerOffer = 10) override val clock: Clock = ConstantClock() override val stateOpProcessor: TaskStateOpProcessor = mock[TaskStateOpProcessor] override def log = mock[LoggingAdapter] } // format: OFF // Different task configuration with startedAt, status since and condition values. Expunge indicates whether an // expunge is expected or not. import f.fiveTen val disabled = UnreachableDisabled val taskCases = Table( ("name", "startedAt", "since", "unreachableStrategy", "condition", "expunge"), ("running", Timestamp.zero, Timestamp.zero, fiveTen, Condition.Running, false ), ("expired inactive", Timestamp.zero, f.clock.now - fiveTen.expungeAfter - 1.minute, fiveTen, Condition.UnreachableInactive, true ), ("unreachable", Timestamp.zero, f.clock.now - 5.minutes, fiveTen, Condition.Unreachable, false ), ("expired disabled", Timestamp.zero, f.clock.now - 365.days, disabled, Condition.Unreachable, false ) ) // format: ON forAll(taskCases) { (name: String, startedAt: Timestamp, since: Timestamp, unreachableStrategy: UnreachableStrategy, condition: Condition, expunge: Boolean) => When(s"filtering $name task since $since") val instance: Instance = (condition match { case Condition.Unreachable => TestInstanceBuilder.newBuilder("/unreachable".toPath).addTaskUnreachable(since = since).getInstance() case Condition.UnreachableInactive => TestInstanceBuilder.newBuilder("/unreachable".toPath).addTaskUnreachableInactive(since = since).getInstance() case _ => TestInstanceBuilder.newBuilder("/running".toPath).addTaskRunning(startedAt = startedAt).getInstance() }).copy(unreachableStrategy = unreachableStrategy) val instances = InstancesBySpec.forInstances(instance).instancesMap val filterForExpunge = businessLogic.filterUnreachableForExpunge(instances, f.clock.now()).map(identity) Then(s"${if (!expunge) "not " else ""}select it for expunge") filterForExpunge.nonEmpty should be(expunge) } When("filtering two running tasks") val running1 = TestInstanceBuilder.newBuilder("/running1".toPath).addTaskRunning(startedAt = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val running2 = TestInstanceBuilder.newBuilder("/running2".toPath).addTaskRunning(startedAt = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val instances = InstancesBySpec.forInstances(running1, running2).instancesMap val filtered = businessLogic.filterUnreachableForExpunge(instances, f.clock.now()).map(identity) Then("return an empty collection") filtered.isEmpty should be(true) When("filtering two expired inactive Unreachable tasks") val inactive1 = TestInstanceBuilder.newBuilder("/unreachable1".toPath).addTaskUnreachableInactive(since = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val inactive2 = TestInstanceBuilder.newBuilder("/unreachable1".toPath).addTaskUnreachableInactive(since = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val instances2 = InstancesBySpec.forInstances(inactive1, inactive2).instancesMap val filtered2 = businessLogic.filterUnreachableForExpunge(instances2, f.clock.now()).map(identity) Then("return the expired Unreachable tasks") filtered2 should be(Iterable(inactive1, inactive2)) } "The ExpungeOverdueLostTaskActor" when { "checking two running tasks" in withActor { (f: Fixture, checkActor: ActorRef) => val running1 = TestInstanceBuilder.newBuilder("/running1".toPath).addTaskRunning(startedAt = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val running2 = TestInstanceBuilder.newBuilder("/running2".toPath).addTaskRunning(startedAt = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) f.taskTracker.instancesBySpec()(any[ExecutionContext]) returns Future.successful(InstancesBySpec.forInstances(running1, running2)) Then("issue no expunge") noMoreInteractions(f.stateOpProcessor) } "checking one inactive Unreachable and one running task" in withActor { (f: Fixture, checkActor: ActorRef) => val running = TestInstanceBuilder.newBuilder("/running".toPath).addTaskRunning(startedAt = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val unreachable = TestInstanceBuilder.newBuilder("/unreachable".toPath).addTaskUnreachableInactive(since = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) f.taskTracker.instancesBySpec()(any[ExecutionContext]) returns Future.successful(InstancesBySpec.forInstances(running, unreachable)) val testProbe = TestProbe() testProbe.send(checkActor, ExpungeOverdueLostTasksActor.Tick) testProbe.receiveOne(3.seconds) Then("issue one expunge") verify(f.stateOpProcessor, once).process(InstanceUpdateOperation.ForceExpunge(unreachable.instanceId)) noMoreInteractions(f.stateOpProcessor) } "checking two inactive Unreachable tasks and one is overdue" in withActor { (f: Fixture, checkActor: ActorRef) => val unreachable1 = TestInstanceBuilder.newBuilder("/unreachable1".toPath).addTaskUnreachableInactive(since = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val unreachable2 = TestInstanceBuilder.newBuilder("/unreachable2".toPath).addTaskUnreachableInactive(since = f.clock.now()) .getInstance() .copy(unreachableStrategy = f.fiveTen) f.taskTracker.instancesBySpec()(any[ExecutionContext]) returns Future.successful(InstancesBySpec.forInstances(unreachable1, unreachable2)) val testProbe = TestProbe() testProbe.send(checkActor, ExpungeOverdueLostTasksActor.Tick) testProbe.receiveOne(3.seconds) Then("issue one expunge") verify(f.stateOpProcessor, once).process(InstanceUpdateOperation.ForceExpunge(unreachable1.instanceId)) noMoreInteractions(f.stateOpProcessor) } "checking two lost task and one is overdue" in withActor { (f: Fixture, checkActor: ActorRef) => // Note that both won't have unreachable time set. val unreachable1 = TestInstanceBuilder.newBuilder("/unreachable1".toPath).addTaskLost(since = Timestamp.zero) .getInstance() .copy(unreachableStrategy = f.fiveTen) val unreachable2 = TestInstanceBuilder.newBuilder("/unreachable2".toPath).addTaskLost(since = f.clock.now()) .getInstance() .copy(unreachableStrategy = f.fiveTen) f.taskTracker.instancesBySpec()(any[ExecutionContext]) returns Future.successful(InstancesBySpec.forInstances(unreachable1, unreachable2)) val testProbe = TestProbe() // Trigger UnreachableInactive mark testProbe.send(checkActor, ExpungeOverdueLostTasksActor.Tick) testProbe.receiveOne(3.seconds) Then("ensure backwards compatibility and issue one expunge") val (taskId, task) = unreachable1.tasksMap.head verify(f.stateOpProcessor, once).process(InstanceUpdateOperation.ForceExpunge(unreachable1.instanceId)) noMoreInteractions(f.stateOpProcessor) } } }
natemurthy/marathon
src/test/scala/mesosphere/marathon/core/task/jobs/ExpungeOverdueLostTasksActorTest.scala
Scala
apache-2.0
9,860
/* * Copyright (C) 2005, The Beangle Software. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.beangle.ems.core.user.model import java.security.Principal import org.beangle.commons.lang.{Numbers, Strings} import org.beangle.data.model.IntId import org.beangle.data.model.pojo._ import org.beangle.ems.core.config.model.Domain /** * @author chaostone */ class Role extends IntId with Named with Updated with Enabled with Hierarchical[Role] with Profile with Principal with Remark { var properties: collection.mutable.Map[Dimension, String] = new collection.mutable.HashMap[Dimension, String] var creator: User = _ var members: collection.mutable.Seq[RoleMember] = new collection.mutable.ListBuffer[RoleMember] var domain: Domain = _ override def getName: String = { name } def index: Int = { if (Strings.isEmpty(indexno)) return 1; val lastPart = Strings.substringAfterLast(indexno, ".") if (lastPart.isEmpty) Numbers.toInt(indexno) else Numbers.toInt(lastPart) } def this(id: Int, name: String) = { this() this.id = id this.name = name } }
beangle/ems
core/src/main/scala/org/beangle/ems/core/user/model/Role.scala
Scala
lgpl-3.0
1,735
package raft import scala.language.postfixOps import akka.actor.{ Actor, ActorRef/*, FSM, LoggingFSM*/ } import scala.concurrent.duration._ import scala.concurrent.Promise import math.random import akka.actor.ActorSystem import akka.actor.Props import akka.worker._ /* messages */ sealed trait Message case object Timeout extends Message case object Heartbeat extends Message case class Init(nodes: List[NodeId]) extends Message case class RequestVote( term: Term, candidateId: NodeId, lastLogIndex: Int, lastLogTerm: Term) extends Message case class AppendEntries( term: Term, leaderId: NodeId, prevLogIndex: Int, prevLogTerm: Term, entries: Vector[Entry], leaderCommit: Int) extends Message sealed trait Vote extends Message case class DenyVote(term: Term) extends Vote case class GrantVote(term: Term) extends Vote sealed trait AppendReply extends Message case class AppendFailure(term: Term) extends AppendReply case class AppendSuccess(term: Term, index: Int) extends AppendReply case class ClientRequest(cid: Int, command: String) extends Message /* Consensus module */ class Raft(val i: Int, val ui: ActorRef) extends Actor /*with LoggingFSM[Role, Meta]*/ { import scala.scalajs.js.timers._ import scala.collection.mutable.HashMap //override def logDepth = 12 var data: Meta = Meta(List()) var state: Role = Initialise val timers = HashMap[String, SetTimeoutHandle]() def cancelTimer(name: String) = { try { clearTimeout(timers(name)) } catch { case _ => } } def setTimer(name: String, kind: Message, timeout: FiniteDuration, bool: Boolean) = timers += name -> setTimeout(timeout) { self ! kind } def switchState(to: Role) = { (state, to) match { case (Leader, Follower) => cancelTimer("heartbeat") resetTimer case (Candidate, Follower) => resetTimer case (Initialise, Follower) => resetTimer case _ => } state = to ui ! UIState(i, state) context.become(to match { case Follower => follower case Candidate => candidate case Leader => leader }) } def receive = { case cluster: Init => data = initialised(cluster) switchState(Follower) } def follower: Receive = { case rpc: RequestVote => vote(rpc, data) match { case (msg: GrantVote, updData) => resetTimer data = updData sender ! msg case (msg: DenyVote, updData) => data = updData sender ! msg } case rpc: AppendEntries => data.setLeader(rpc.leaderId) resetTimer val msg = append(rpc, data) sender ! msg case rpc: ClientRequest => forwardRequest(rpc, data) case Timeout => data = preparedForCandidate(data) switchState(Candidate) } def candidate: Receive = { // voting events case GrantVote(term) => data.votes = data.votes.gotVoteFrom(sender) if (data.votes.majority(data.nodes.length)) data = preparedForLeader(data) switchState(Leader) case DenyVote(term) => if (term > data.term) { data.selectTerm(term) data = preparedForFollower(data) switchState(Follower) } // other case rpc: AppendEntries => data.setLeader(rpc.leaderId) val msg = append(rpc, data) data = preparedForFollower(data) sender ! msg switchState(Follower) case rpc: ClientRequest => forwardRequest(rpc, data) case Timeout => data = preparedForCandidate(data) switchState(Candidate) } def leader: Receive = { case clientRpc: ClientRequest => writeToLog(sender, clientRpc, data) sendEntries(data) case rpc: AppendSuccess => data.log = data.log.resetNextFor(sender) data.log = data.log.matchFor(sender, Some(rpc.index)) leaderCommitEntries(rpc, data) applyEntries(data) case rpc: AppendFailure => if (rpc.term <= data.term) { data.log = data.log.decrementNextFor(sender) resendTo(sender, data) // let heartbeats do the catch up work } else { data.term = rpc.term data = preparedForFollower(data) switchState(Follower) } case Heartbeat => ui ! UIHeartbeat(i) sendEntries(data) } /* startWith(Initialise, Meta(List())) when(Initialise) { case Event(cluster: Init, _) => goto(Follower) using initialised(cluster) } when(Follower) { case Event(rpc: RequestVote, data) => vote(rpc, data) match { case (msg: GrantVote, updData) => resetTimer stay using (updData) replying (msg) case (msg: DenyVote, updData) => stay using (updData) replying (msg) } case Event(rpc: AppendEntries, data) => data.setLeader(rpc.leaderId) resetTimer val msg = append(rpc, data) stay using data replying msg case Event(rpc: ClientRequest, data) => forwardRequest(rpc, data) stay case Event(Timeout, data) => goto(Candidate) using preparedForCandidate(data) } when(Candidate) { // voting events case Event(GrantVote(term), data: Meta) => data.votes = data.votes.gotVoteFrom(sender) if (data.votes.majority(data.nodes.length)) goto(Leader) using preparedForLeader(data) else stay using data case Event(DenyVote(term), data: Meta) => if (term > data.term) { data.selectTerm(term) goto(Follower) using preparedForFollower(data) } else stay // other case Event(rpc: AppendEntries, data: Meta) => data.setLeader(rpc.leaderId) val msg = append(rpc, data) goto(Follower) using preparedForFollower(data) replying msg case Event(rpc: ClientRequest, data) => forwardRequest(rpc, data) stay case Event(Timeout, data: Meta) => goto(Candidate) using preparedForCandidate(data) } when(Leader) { case Event(clientRpc: ClientRequest, data: Meta) => writeToLog(sender, clientRpc, data) sendEntries(data) stay using data case Event(rpc: AppendSuccess, data: Meta) => data.log = data.log.resetNextFor(sender) data.log = data.log.matchFor(sender, Some(rpc.index)) leaderCommitEntries(rpc, data) applyEntries(data) stay case Event(rpc: AppendFailure, data: Meta) => if (rpc.term <= data.term) { data.log = data.log.decrementNextFor(sender) //resendTo(sender, data) // let heartbeats do the catch up work stay } else { data.term = rpc.term goto(Follower) using preparedForFollower(data) } case Event(Heartbeat, data: Meta) => sendEntries(data) stay } onTermination { case StopEvent(FSM.Failure(cause), state, data) => val lastEvents = getLog.mkString("\n\t") log.warning(s"Failure in state $state with data $data due to $cause" + "Events leading up to this: \n\t$lastEvents") }*/ private def preparedForFollower(state: Meta): Meta = { state.votes = Votes() state } private def preparedForCandidate(data: Meta): Meta = { data.nextTerm data.votes = Votes(votedFor = Some(self), received = List(self)) data.nodes.filter(_ != self).map { t => t ! RequestVote( term = data.term, candidateId = self, lastLogIndex = data.log.entries.lastIndex, lastLogTerm = data.log.entries.lastTerm) } resetTimer data } private def preparedForLeader(state: Meta) = { //log.info(s"Elected to leader for term: ${state.term}") val nexts = state.log.nextIndex.map(x => (x._1, state.log.entries.lastIndex + 1)) val matches = state.log.matchIndex.map(x => (x._1, 0)) state.log = state.log.copy(nextIndex = nexts, matchIndex = matches) sendEntries(state) state } private def initialised(cluster: Init): Meta = Meta(cluster.nodes) private def resetHeartbeatTimer = { cancelTimer("heartbeat") val nextTimeout = (random * 100).toInt + 100 setTimer("heartbeat", Heartbeat, nextTimeout millis, false) } private def resetTimer = { cancelTimer("timeout") val nextTimeout = (random * 100).toInt + 200 setTimer("timeout", Timeout, nextTimeout millis, false) } //initialize() // akka specific /* * --- Internals --- */ private def forwardRequest(rpc: ClientRequest, data: Meta) = { data.leader match { case Some(target) => target forward rpc case None => // drops message, relies on client to retry } } private def applyEntries(data: Meta) = for (i <- data.log.lastApplied until data.log.commitIndex) { val entry = data.log.entries(i) val result = data.rsm.execute(Get) // TODO: make generic data.log = data.log.applied entry.client match { case Some(ref) => ref.sender ! (ref.cid, result) case None => // ignore } } private def leaderCommitEntries(rpc: AppendSuccess, data: Meta) = { if (rpc.index >= data.log.commitIndex && data.log.entries.termOf(rpc.index) == data.term) { val matches = data.log.matchIndex.count(_._2 == rpc.index) if (matches >= Math.ceil(data.nodes.length / 2.0)) data.log = data.log.commit(rpc.index) } } private def sendEntries(data: Meta) = { resetHeartbeatTimer data.nodes.filterNot(_ == self).map { node => val message = compileMessage(node, data) node ! message } } private def resendTo(node: NodeId, data: Meta) = { val message = compileMessage(node, data) node ! message } private def compileMessage(node: ActorRef, data: Meta): AppendEntries = { val prevIndex = data.log.nextIndex(node) - 1 val prevTerm = data.log.entries.termOf(prevIndex) val fromMissing = missingRange(data.log.entries.lastIndex, prevIndex) AppendEntries( term = data.term, leaderId = self, prevLogIndex = prevIndex, prevLogTerm = prevTerm, entries = data.log.entries.takeRight(fromMissing), leaderCommit = data.log.commitIndex ) } private def missingRange(lastIndex: Int, prevIndex: Int) = if (prevIndex == 0) 1 else lastIndex - prevIndex private def writeToLog(sender: NodeId, rpc: ClientRequest, data: Meta) = { val ref = InternalClientRef(sender, rpc.cid) val entry = Entry(rpc.command, data.term, Some(ref)) data.leaderAppend(self, Vector(entry)) } /* * AppendEntries handling */ private def append(rpc: AppendEntries, data: Meta): AppendReply = { if (leaderIsBehind(rpc, data)) appendFail(rpc, data) else if (!hasMatchingLogEntryAtPrevPosition(rpc, data)) appendFail(rpc, data) else appendSuccess(rpc, data) } private def leaderIsBehind(rpc: AppendEntries, data: Meta): Boolean = rpc.term < data.term private def hasMatchingLogEntryAtPrevPosition( rpc: AppendEntries, data: Meta): Boolean = (rpc.prevLogIndex == 0 || // guards for bootstrap case (data.log.entries.hasEntryAt(rpc.prevLogIndex) && (data.log.entries.termOf(rpc.prevLogIndex) == rpc.prevLogTerm))) private def appendFail(rpc: AppendEntries, data: Meta) = { data.selectTerm(rpc.term) AppendFailure(data.term) } private def appendSuccess(rpc: AppendEntries, data: Meta) = { data.append(rpc.entries, rpc.prevLogIndex) data.log = data.log.commit(rpc.leaderCommit) followerApplyEntries(data) data.selectTerm(rpc.term) AppendSuccess(data.term, data.log.entries.lastIndex) } private def followerApplyEntries(data: Meta) = for (i <- data.log.lastApplied until data.log.commitIndex) { val entry = data.log.entries(i) data.rsm.execute(Get) // TODO: make generic data.log = data.log.applied } /* * Determine whether to grant or deny vote */ private def vote(rpc: RequestVote, data: Meta): (Vote, Meta) = if (alreadyVoted(rpc, data)) deny(rpc, data) else if (rpc.term < data.term) deny(rpc, data) else if (rpc.term == data.term) if (candidateLogTermIsBehind(rpc, data)) deny(rpc, data) else if (candidateLogTermIsEqualButHasShorterLog(rpc, data)) deny(rpc, data) else grant(rpc, data) // follower and candidate are equal, grant else grant(rpc, data) // candidate is ahead, grant private def deny(rpc: RequestVote, data: Meta) = { data.term = Term.max(data.term, rpc.term) (DenyVote(data.term), data) } private def grant(rpc: RequestVote, data: Meta): (Vote, Meta) = { data.votes = data.votes.vote(rpc.candidateId) data.term = Term.max(data.term, rpc.term) (GrantVote(data.term), data) } private def candidateLogTermIsBehind(rpc: RequestVote, data: Meta) = data.log.entries.last.term > rpc.lastLogTerm private def candidateLogTermIsEqualButHasShorterLog(rpc: RequestVote, data: Meta) = (data.log.entries.last.term == rpc.lastLogTerm) && (data.log.entries.length - 1 > rpc.lastLogIndex) private def alreadyVoted(rpc: RequestVote, data: Meta): Boolean = data.votes.votedFor match { case Some(_) if rpc.term == data.term => true case Some(_) if rpc.term > data.term => false case None => false } } object Raft { def apply(size: Int, ui: ActorRef)(implicit system: ActorSystem): List[NodeId] = { val members = for (i <- List.range(0, size)) yield system.actorOf(Props(classOf[Raft], i, ui), "member" + i) members.foreach(m => m ! Init(members)) members } }
jmnarloch/akka.js
akka-js-worker/raft/src/main/scala/raft/Raft.scala
Scala
bsd-3-clause
13,490
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.hive import java.sql.Timestamp import java.util.{Locale, TimeZone} import org.apache.hadoop.hive.conf.HiveConf import org.scalatest.BeforeAndAfterAll import org.apache.spark.sql.execution.datasources.parquet.ParquetCompatibilityTest import org.apache.spark.sql.hive.test.TestHive import org.apache.spark.sql.{Row, SQLConf, SQLContext} class ParquetHiveCompatibilitySuite extends ParquetCompatibilityTest with BeforeAndAfterAll { override def _sqlContext: SQLContext = TestHive private val sqlContext = _sqlContext /** * Set the staging directory (and hence path to ignore Parquet files under) * to that set by [[HiveConf.ConfVars.STAGINGDIR]]. */ private val stagingDir = new HiveConf().getVar(HiveConf.ConfVars.STAGINGDIR) private val originalTimeZone = TimeZone.getDefault private val originalLocale = Locale.getDefault protected override def beforeAll(): Unit = { TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")) Locale.setDefault(Locale.US) } override protected def afterAll(): Unit = { TimeZone.setDefault(originalTimeZone) Locale.setDefault(originalLocale) } override protected def logParquetSchema(path: String): Unit = { val schema = readParquetSchema(path, { path => !path.getName.startsWith("_") && !path.getName.startsWith(stagingDir) }) logInfo( s"""Schema of the Parquet file written by parquet-avro: |$schema """.stripMargin) } private def testParquetHiveCompatibility(row: Row, hiveTypes: String*): Unit = { withTable("parquet_compat") { withTempPath { dir => val path = dir.getCanonicalPath // Hive columns are always nullable, so here we append a all-null row. val rows = row :: Row(Seq.fill(row.length)(null): _*) :: Nil // Don't convert Hive metastore Parquet tables to let Hive write those Parquet files. withSQLConf(HiveContext.CONVERT_METASTORE_PARQUET.key -> "false") { withTempTable("data") { val fields = hiveTypes.zipWithIndex.map { case (typ, index) => s" col_$index $typ" } val ddl = s"""CREATE TABLE parquet_compat( |${fields.mkString(",\\n")} |) |STORED AS PARQUET |LOCATION '$path' """.stripMargin logInfo( s"""Creating testing Parquet table with the following DDL: |$ddl """.stripMargin) sqlContext.sql(ddl) val schema = sqlContext.table("parquet_compat").schema val rowRDD = sqlContext.sparkContext.parallelize(rows).coalesce(1) sqlContext.createDataFrame(rowRDD, schema).registerTempTable("data") sqlContext.sql("INSERT INTO TABLE parquet_compat SELECT * FROM data") } } logParquetSchema(path) // Unfortunately parquet-hive doesn't add `UTF8` annotation to BINARY when writing strings. // Have to assume all BINARY values are strings here. withSQLConf(SQLConf.PARQUET_BINARY_AS_STRING.key -> "true") { checkAnswer(sqlContext.read.parquet(path), rows) } } } } test("simple primitives") { testParquetHiveCompatibility( Row(true, 1.toByte, 2.toShort, 3, 4.toLong, 5.1f, 6.1d, "foo"), "BOOLEAN", "TINYINT", "SMALLINT", "INT", "BIGINT", "FLOAT", "DOUBLE", "STRING") } test("SPARK-10177 timestamp") { testParquetHiveCompatibility(Row(Timestamp.valueOf("2015-08-24 00:31:00")), "TIMESTAMP") } test("array") { testParquetHiveCompatibility( Row( Seq[Integer](1: Integer, null, 2: Integer, null), Seq[String]("foo", null, "bar", null), Seq[Seq[Integer]]( Seq[Integer](1: Integer, null), Seq[Integer](2: Integer, null))), "ARRAY<INT>", "ARRAY<STRING>", "ARRAY<ARRAY<INT>>") } test("map") { testParquetHiveCompatibility( Row( Map[Integer, String]( (1: Integer) -> "foo", (2: Integer) -> null)), "MAP<INT, STRING>") } // HIVE-11625: Parquet map entries with null keys are dropped by Hive ignore("map entries with null keys") { testParquetHiveCompatibility( Row( Map[Integer, String]( null.asInstanceOf[Integer] -> "bar", null.asInstanceOf[Integer] -> null)), "MAP<INT, STRING>") } test("struct") { testParquetHiveCompatibility( Row(Row(1, Seq("foo", "bar", null))), "STRUCT<f0: INT, f1: ARRAY<STRING>>") } }
ArvinDevel/onlineAggregationOnSparkV2
sql/hive/src/test/scala/org/apache/spark/sql/hive/ParquetHiveCompatibilitySuite.scala
Scala
apache-2.0
5,393
abstract class Base { def f: Int val a = f // error } class Derived extends Base { def f = g private def g: Int = 30 } class Derived2 extends Base { val b = 30 // error def f = g def g: Int = b + a }
som-snytt/dotty
tests/init/neg/override27.scala
Scala
apache-2.0
238
/* * Copyright 2015 eleflow.com.br. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eleflow.sparknotebook import sun.misc.{Signal,SignalHandler} import org.zeromq.ZMQ import scalax.io.JavaConverters._ import scalax.file.Path import org.refptr.iscala._ import json.JsonUtil._ import msg._ object Main extends App { val options = new Options(args) val thread = new Thread { override def run() { val iscala = new IScala(options.config){ override lazy val interpreter = new SparkNotebookInterpreter(classpath, options.config.args) } iscala.heartBeat.join() } } thread.setName("IScala") thread.setDaemon(true) thread.start() thread.join() }
eleflow/sparknotebook
src/main/scala/eleflow/sparknotebook/Main.scala
Scala
apache-2.0
1,198
/* * Copyright 2011-2018 GatlingCorp (http://gatling.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gatling.jms.action import javax.jms.Message import io.gatling.commons.validation._ import io.gatling.core.action.RequestAction import io.gatling.core.session._ import io.gatling.core.util.NameGen import io.gatling.jms.client.{ JmsConnection, JmsConnectionPool } import io.gatling.jms.protocol.JmsProtocol import io.gatling.jms.request._ abstract class JmsAction(attributes: JmsAttributes, protocol: JmsProtocol, pool: JmsConnectionPool) extends RequestAction with JmsLogging with NameGen { override val requestName: Expression[String] = attributes.requestName protected val jmsConnection: JmsConnection = pool.jmsConnection(protocol.connectionFactory, protocol.credentials) private val jmsDestination = jmsConnection.destination(attributes.destination) override def sendRequest(requestName: String, session: Session): Validation[Unit] = for { jmsType <- resolveOptionalExpression(attributes.jmsType, session) props <- resolveProperties(attributes.messageProperties, session) resolvedJmsDestination <- jmsDestination(session) beforeSend0 <- beforeSend(requestName, session) } yield { val producer = jmsConnection.producer(resolvedJmsDestination, protocol.deliveryMode) attributes.message match { case BytesJmsMessage(bytes) => bytes(session).map(bytes => producer.sendBytesMessage(bytes, props, jmsType, beforeSend0)) case MapJmsMessage(map) => map(session).map(map => producer.sendMapMessage(map, props, jmsType, beforeSend0)) case ObjectJmsMessage(o) => o(session).map(o => producer.sendObjectMessage(o, props, jmsType, beforeSend0)) case TextJmsMessage(txt) => txt(session).map(txt => producer.sendTextMessage(txt, props, jmsType, beforeSend0)) } } private def resolveProperties( properties: Map[Expression[String], Expression[Any]], session: Session ): Validation[Map[String, Any]] = properties.foldLeft(Map.empty[String, Any].success) { case (resolvedProperties, (key, value)) => for { key <- key(session) value <- value(session) resolvedProperties <- resolvedProperties } yield resolvedProperties + (key -> value) } protected def beforeSend(requestName: String, session: Session): Validation[Message => Unit] }
wiacekm/gatling
gatling-jms/src/main/scala/io/gatling/jms/action/JmsAction.scala
Scala
apache-2.0
2,936
package scala.collection.parallel import org.scalacheck._ import org.scalacheck.Gen import org.scalacheck.Gen._ import org.scalacheck.Prop._ import org.scalacheck.Properties import scala.collection._ import scala.collection.parallel._ abstract class ParallelMapCheck[K, V](collname: String) extends ParallelIterableCheck[(K, V)](collname) { type CollType <: ParMap[K, V] property("gets iterated keys") = forAllNoShrink(collectionPairs) { case (t, coll) => val containsT = for ((k, v) <- t) yield (coll.get(k) == Some(v)) val containsSelf = coll.map { case (k, v) => coll.get(k) == Some(v) } ("Par contains elements of seq map" |: containsT.forall(_ == true)) && ("Par contains elements of itself" |: containsSelf.forall(_ == true)) } }
shimib/scala
test/scalacheck/scala/collection/parallel/ParallelMapCheck1.scala
Scala
bsd-3-clause
811
package com.atomist.source.git.domain import com.atomist.source.FileArtifact private[git] case class FileWithBlobRef(fa: FileArtifact, ref: GitHubRef)
atomist/artifact-source
src/main/scala/com/atomist/source/git/domain/FileWithBlobRef.scala
Scala
gpl-3.0
152
/* * Copyright 2012 Twitter Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.zipkin.hadoop import com.twitter.scalding.{Tsv, DefaultDateRangeJob, Job, Args} import com.twitter.zipkin.gen.{SpanServiceName, Annotation} import com.twitter.zipkin.hadoop.sources.{TimeGranularity, PreprocessedSpanSource} /** * Finds traces with duplicate trace IDs */ class FindDuplicateTraces(args: Args) extends Job(args) with DefaultDateRangeJob { val maxDuration = augmentString(args.required("maximum_duration")).toInt val result = PreprocessedSpanSource(TimeGranularity.Hour) .read .mapTo(0 ->('trace_id, 'annotations)) { s: SpanServiceName => (s.trace_id, s.annotations.toList) }.flatMap('annotations -> 'first_and_last_timestamps ) {al : List[Annotation] => var first : Long = if (al.length > 0) al(0).timestamp else Int.MaxValue var last : Long = if (al.length > 0) al(0).timestamp else -1 al.foreach { a : Annotation => val timestamp = a.timestamp if (timestamp < first) first = timestamp else if (timestamp > last) last = timestamp } if (first < Int.MaxValue && last > -1) Some(List(first, last)) else None }.groupBy('trace_id){ _.reduce('first_and_last_timestamps -> 'first_and_last_timestamps) { (left : List[Long], right : List[Long]) => val first = if (left(0) > right(0)) right(0) else left(0) val last = if (left(1) > right(1)) left(1) else right(1) List(first, last) } } .filter('first_and_last_timestamps) { timestamps : List[Long] => val durationInSeconds = (timestamps(1) - timestamps(0)) / 1000000 durationInSeconds >= maxDuration }.project('trace_id) .write(Tsv(args("output"))) }
netconstructor/zipkin
zipkin-hadoop/src/main/scala/com/twitter/zipkin/hadoop/FindDuplicateTraces.scala
Scala
apache-2.0
2,268
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql import java.util.Properties import scala.collection.JavaConverters._ import org.apache.spark.sql.catalyst.TableIdentifier import org.apache.spark.sql.catalyst.analysis.UnresolvedRelation import org.apache.spark.sql.catalyst.plans.logical.{InsertIntoTable, Project} import org.apache.spark.sql.execution.datasources.{BucketSpec, CreateTableUsingAsSelect, DataSource, HadoopFsRelation} import org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils /** * Interface used to write a [[Dataset]] to external storage systems (e.g. file systems, * key-value stores, etc). Use [[Dataset.write]] to access this. * * @since 1.4.0 */ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) { private val df = ds.toDF() /** * Specifies the behavior when data or table already exists. Options include: * - `SaveMode.Overwrite`: overwrite the existing data. * - `SaveMode.Append`: append the data. * - `SaveMode.Ignore`: ignore the operation (i.e. no-op). * - `SaveMode.ErrorIfExists`: default option, throw an exception at runtime. * * @since 1.4.0 */ def mode(saveMode: SaveMode): DataFrameWriter[T] = { this.mode = saveMode this } /** * Specifies the behavior when data or table already exists. Options include: * - `overwrite`: overwrite the existing data. * - `append`: append the data. * - `ignore`: ignore the operation (i.e. no-op). * - `error`: default option, throw an exception at runtime. * * @since 1.4.0 */ def mode(saveMode: String): DataFrameWriter[T] = { this.mode = saveMode.toLowerCase match { case "overwrite" => SaveMode.Overwrite case "append" => SaveMode.Append case "ignore" => SaveMode.Ignore case "error" | "default" => SaveMode.ErrorIfExists case _ => throw new IllegalArgumentException(s"Unknown save mode: $saveMode. " + "Accepted save modes are 'overwrite', 'append', 'ignore', 'error'.") } this } /** * Specifies the underlying output data source. Built-in options include "parquet", "json", etc. * * @since 1.4.0 */ def format(source: String): DataFrameWriter[T] = { this.source = source this } /** * Adds an output option for the underlying data source. * * @since 1.4.0 */ def option(key: String, value: String): DataFrameWriter[T] = { this.extraOptions += (key -> value) this } /** * Adds an output option for the underlying data source. * * @since 2.0.0 */ def option(key: String, value: Boolean): DataFrameWriter[T] = option(key, value.toString) /** * Adds an output option for the underlying data source. * * @since 2.0.0 */ def option(key: String, value: Long): DataFrameWriter[T] = option(key, value.toString) /** * Adds an output option for the underlying data source. * * @since 2.0.0 */ def option(key: String, value: Double): DataFrameWriter[T] = option(key, value.toString) /** * (Scala-specific) Adds output options for the underlying data source. * * @since 1.4.0 */ def options(options: scala.collection.Map[String, String]): DataFrameWriter[T] = { this.extraOptions ++= options this } /** * Adds output options for the underlying data source. * * @since 1.4.0 */ def options(options: java.util.Map[String, String]): DataFrameWriter[T] = { this.options(options.asScala) this } /** * Partitions the output by the given columns on the file system. If specified, the output is * laid out on the file system similar to Hive's partitioning scheme. As an example, when we * partition a dataset by year and then month, the directory layout would look like: * * - year=2016/month=01/ * - year=2016/month=02/ * * Partitioning is one of the most widely used techniques to optimize physical data layout. * It provides a coarse-grained index for skipping unnecessary data reads when queries have * predicates on the partitioned columns. In order for partitioning to work well, the number * of distinct values in each column should typically be less than tens of thousands. * * This was initially applicable for Parquet but in 1.5+ covers JSON, text, ORC and avro as well. * * @since 1.4.0 */ @scala.annotation.varargs def partitionBy(colNames: String*): DataFrameWriter[T] = { this.partitioningColumns = Option(colNames) this } /** * Buckets the output by the given columns. If specified, the output is laid out on the file * system similar to Hive's bucketing scheme. * * This is applicable for Parquet, JSON and ORC. * * @since 2.0 */ @scala.annotation.varargs def bucketBy(numBuckets: Int, colName: String, colNames: String*): DataFrameWriter[T] = { this.numBuckets = Option(numBuckets) this.bucketColumnNames = Option(colName +: colNames) this } /** * Sorts the output in each bucket by the given columns. * * This is applicable for Parquet, JSON and ORC. * * @since 2.0 */ @scala.annotation.varargs def sortBy(colName: String, colNames: String*): DataFrameWriter[T] = { this.sortColumnNames = Option(colName +: colNames) this } /** * Saves the content of the [[DataFrame]] at the specified path. * * @since 1.4.0 */ def save(path: String): Unit = { this.extraOptions += ("path" -> path) save() } /** * Saves the content of the [[DataFrame]] as the specified table. * * @since 1.4.0 */ def save(): Unit = { assertNotBucketed("save") val dataSource = DataSource( df.sparkSession, className = source, partitionColumns = partitioningColumns.getOrElse(Nil), bucketSpec = getBucketSpec, options = extraOptions.toMap) dataSource.write(mode, df) } /** * Inserts the content of the [[DataFrame]] to the specified table. It requires that * the schema of the [[DataFrame]] is the same as the schema of the table. * * Note: Unlike `saveAsTable`, `insertInto` ignores the column names and just uses position-based * resolution. For example: * * {{{ * scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1") * scala> Seq((3, 4)).toDF("j", "i").write.insertInto("t1") * scala> Seq((5, 6)).toDF("a", "b").write.insertInto("t1") * scala> sql("select * from t1").show * +---+---+ * | i| j| * +---+---+ * | 5| 6| * | 3| 4| * | 1| 2| * +---+---+ * }}} * * Because it inserts data to an existing table, format or options will be ignored. * * @since 1.4.0 */ def insertInto(tableName: String): Unit = { insertInto(df.sparkSession.sessionState.sqlParser.parseTableIdentifier(tableName)) } private def insertInto(tableIdent: TableIdentifier): Unit = { assertNotBucketed("insertInto") if (partitioningColumns.isDefined) { throw new AnalysisException( "insertInto() can't be used together with partitionBy(). " + "Partition columns have already be defined for the table. " + "It is not necessary to use partitionBy()." ) } df.sparkSession.sessionState.executePlan( InsertIntoTable( table = UnresolvedRelation(tableIdent), partition = Map.empty[String, Option[String]], child = df.logicalPlan, overwrite = mode == SaveMode.Overwrite, ifNotExists = false)).toRdd } private def normalizedParCols: Option[Seq[String]] = partitioningColumns.map { cols => cols.map(normalize(_, "Partition")) } private def normalizedBucketColNames: Option[Seq[String]] = bucketColumnNames.map { cols => cols.map(normalize(_, "Bucketing")) } private def normalizedSortColNames: Option[Seq[String]] = sortColumnNames.map { cols => cols.map(normalize(_, "Sorting")) } private def getBucketSpec: Option[BucketSpec] = { if (sortColumnNames.isDefined) { require(numBuckets.isDefined, "sortBy must be used together with bucketBy") } for { n <- numBuckets } yield { require(n > 0 && n < 100000, "Bucket number must be greater than 0 and less than 100000.") // partitionBy columns cannot be used in bucketBy if (normalizedParCols.nonEmpty && normalizedBucketColNames.get.toSet.intersect(normalizedParCols.get.toSet).nonEmpty) { throw new AnalysisException( s"bucketBy columns '${bucketColumnNames.get.mkString(", ")}' should not be part of " + s"partitionBy columns '${partitioningColumns.get.mkString(", ")}'") } BucketSpec(n, normalizedBucketColNames.get, normalizedSortColNames.getOrElse(Nil)) } } /** * The given column name may not be equal to any of the existing column names if we were in * case-insensitive context. Normalize the given column name to the real one so that we don't * need to care about case sensitivity afterwards. */ private def normalize(columnName: String, columnType: String): String = { val validColumnNames = df.logicalPlan.output.map(_.name) validColumnNames.find(df.sparkSession.sessionState.analyzer.resolver(_, columnName)) .getOrElse(throw new AnalysisException(s"$columnType column $columnName not found in " + s"existing columns (${validColumnNames.mkString(", ")})")) } private def assertNotBucketed(operation: String): Unit = { if (numBuckets.isDefined || sortColumnNames.isDefined) { throw new AnalysisException(s"'$operation' does not support bucketing right now") } } private def assertNotPartitioned(operation: String): Unit = { if (partitioningColumns.isDefined) { throw new AnalysisException( s"'$operation' does not support partitioning") } } /** * Saves the content of the [[DataFrame]] as the specified table. * * In the case the table already exists, behavior of this function depends on the * save mode, specified by the `mode` function (default to throwing an exception). * When `mode` is `Overwrite`, the schema of the [[DataFrame]] does not need to be * the same as that of the existing table. * * When `mode` is `Append`, if there is an existing table, we will use the format and options of * the existing table. The column order in the schema of the [[DataFrame]] doesn't need to be same * as that of the existing table. Unlike `insertInto`, `saveAsTable` will use the column names to * find the correct column positions. For example: * * {{{ * scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1") * scala> Seq((3, 4)).toDF("j", "i").write.mode("append").saveAsTable("t1") * scala> sql("select * from t1").show * +---+---+ * | i| j| * +---+---+ * | 1| 2| * | 4| 3| * +---+---+ * }}} * * When the DataFrame is created from a non-partitioned [[HadoopFsRelation]] with a single input * path, and the data source provider can be mapped to an existing Hive builtin SerDe (i.e. ORC * and Parquet), the table is persisted in a Hive compatible format, which means other systems * like Hive will be able to read this table. Otherwise, the table is persisted in a Spark SQL * specific format. * * @since 1.4.0 */ def saveAsTable(tableName: String): Unit = { saveAsTable(df.sparkSession.sessionState.sqlParser.parseTableIdentifier(tableName)) } private def saveAsTable(tableIdent: TableIdentifier): Unit = { val tableExists = df.sparkSession.sessionState.catalog.tableExists(tableIdent) (tableExists, mode) match { case (true, SaveMode.Ignore) => // Do nothing case (true, SaveMode.ErrorIfExists) => throw new AnalysisException(s"Table $tableIdent already exists.") case _ => val cmd = CreateTableUsingAsSelect( tableIdent, source, partitioningColumns.map(_.toArray).getOrElse(Array.empty[String]), getBucketSpec, mode, extraOptions.toMap, df.logicalPlan) df.sparkSession.sessionState.executePlan(cmd).toRdd } } /** * Saves the content of the [[DataFrame]] to an external database table via JDBC. In the case the * table already exists in the external database, behavior of this function depends on the * save mode, specified by the `mode` function (default to throwing an exception). * * Don't create too many partitions in parallel on a large cluster; otherwise Spark might crash * your external database systems. * * @param url JDBC database url of the form `jdbc:subprotocol:subname` * @param table Name of the table in the external database. * @param connectionProperties JDBC database connection arguments, a list of arbitrary string * tag/value. Normally at least a "user" and "password" property * should be included. "batchsize" can be used to control the * number of rows per insert. * @since 1.4.0 */ def jdbc(url: String, table: String, connectionProperties: Properties): Unit = { assertNotPartitioned("jdbc") assertNotBucketed("jdbc") val props = new Properties() extraOptions.foreach { case (key, value) => props.put(key, value) } // connectionProperties should override settings in extraOptions props.putAll(connectionProperties) val conn = JdbcUtils.createConnectionFactory(url, props)() try { var tableExists = JdbcUtils.tableExists(conn, url, table) if (mode == SaveMode.Ignore && tableExists) { return } if (mode == SaveMode.ErrorIfExists && tableExists) { sys.error(s"Table $table already exists.") } if (mode == SaveMode.Overwrite && tableExists) { JdbcUtils.dropTable(conn, table) tableExists = false } // Create the table if the table didn't exist. if (!tableExists) { val schema = JdbcUtils.schemaString(df, url) val sql = s"CREATE TABLE $table ($schema)" val statement = conn.createStatement try { statement.executeUpdate(sql) } finally { statement.close() } } } finally { conn.close() } JdbcUtils.saveTable(df, url, table, props) } /** * Saves the content of the [[DataFrame]] in JSON format at the specified path. * This is equivalent to: * {{{ * format("json").save(path) * }}} * * You can set the following JSON-specific option(s) for writing JSON files: * <ul> * <li>`compression` (default `null`): compression codec to use when saving to file. This can be * one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`, * `snappy` and `deflate`). </li> * <li>`dateFormat` (default `yyyy-MM-dd`): sets the string that indicates a date format. * Custom date formats follow the formats at `java.text.SimpleDateFormat`. This applies to * date type.</li> * <li>`timestampFormat` (default `yyyy-MM-dd'T'HH:mm:ss.SSSZZ`): sets the string that * indicates a timestamp format. Custom date formats follow the formats at * `java.text.SimpleDateFormat`. This applies to timestamp type.</li> * </ul> * * @since 1.4.0 */ def json(path: String): Unit = { format("json").save(path) } /** * Saves the content of the [[DataFrame]] in Parquet format at the specified path. * This is equivalent to: * {{{ * format("parquet").save(path) * }}} * * You can set the following Parquet-specific option(s) for writing Parquet files: * <ul> * <li>`compression` (default is the value specified in `spark.sql.parquet.compression.codec`): * compression codec to use when saving to file. This can be one of the known case-insensitive * shorten names(none, `snappy`, `gzip`, and `lzo`). This will override * `spark.sql.parquet.compression.codec`.</li> * </ul> * * @since 1.4.0 */ def parquet(path: String): Unit = { format("parquet").save(path) } /** * Saves the content of the [[DataFrame]] in ORC format at the specified path. * This is equivalent to: * {{{ * format("orc").save(path) * }}} * * You can set the following ORC-specific option(s) for writing ORC files: * <ul> * <li>`compression` (default `snappy`): compression codec to use when saving to file. This can be * one of the known case-insensitive shorten names(`none`, `snappy`, `zlib`, and `lzo`). * This will override `orc.compress`.</li> * </ul> * * @since 1.5.0 * @note Currently, this method can only be used after enabling Hive support */ def orc(path: String): Unit = { format("orc").save(path) } /** * Saves the content of the [[DataFrame]] in a text file at the specified path. * The DataFrame must have only one column that is of string type. * Each row becomes a new line in the output file. For example: * {{{ * // Scala: * df.write.text("/path/to/output") * * // Java: * df.write().text("/path/to/output") * }}} * * You can set the following option(s) for writing text files: * <ul> * <li>`compression` (default `null`): compression codec to use when saving to file. This can be * one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`, * `snappy` and `deflate`). </li> * </ul> * * @since 1.6.0 */ def text(path: String): Unit = { format("text").save(path) } /** * Saves the content of the [[DataFrame]] in CSV format at the specified path. * This is equivalent to: * {{{ * format("csv").save(path) * }}} * * You can set the following CSV-specific option(s) for writing CSV files: * <ul> * <li>`sep` (default `,`): sets the single character as a separator for each * field and value.</li> * <li>`quote` (default `"`): sets the single character used for escaping quoted values where * the separator can be part of the value.</li> * <li>`escape` (default `\\`): sets the single character used for escaping quotes inside * an already quoted value.</li> * <li>`escapeQuotes` (default `true`): a flag indicating whether values containing * quotes should always be enclosed in quotes. Default is to escape all values containing * a quote character.</li> * <li>`quoteAll` (default `false`): A flag indicating whether all values should always be * enclosed in quotes. Default is to only escape values containing a quote character.</li> * <li>`header` (default `false`): writes the names of columns as the first line.</li> * <li>`nullValue` (default empty string): sets the string representation of a null value.</li> * <li>`compression` (default `null`): compression codec to use when saving to file. This can be * one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`, * `snappy` and `deflate`). </li> * <li>`dateFormat` (default `yyyy-MM-dd`): sets the string that indicates a date format. * Custom date formats follow the formats at `java.text.SimpleDateFormat`. This applies to * date type.</li> * <li>`timestampFormat` (default `yyyy-MM-dd'T'HH:mm:ss.SSSZZ`): sets the string that * indicates a timestamp format. Custom date formats follow the formats at * `java.text.SimpleDateFormat`. This applies to timestamp type.</li> * </ul> * * @since 2.0.0 */ def csv(path: String): Unit = { format("csv").save(path) } /////////////////////////////////////////////////////////////////////////////////////// // Builder pattern config options /////////////////////////////////////////////////////////////////////////////////////// private var source: String = df.sparkSession.sessionState.conf.defaultDataSourceName private var mode: SaveMode = SaveMode.ErrorIfExists private var extraOptions = new scala.collection.mutable.HashMap[String, String] private var partitioningColumns: Option[Seq[String]] = None private var bucketColumnNames: Option[Seq[String]] = None private var numBuckets: Option[Int] = None private var sortColumnNames: Option[Seq[String]] = None }
gioenn/xSpark
sql/core/src/main/scala/org/apache/spark/sql/DataFrameWriter.scala
Scala
apache-2.0
21,070
package org.scalafmt.internal import scala.meta.tokens.Token import org.scalafmt.internal.Length.Num import org.scalafmt.internal.Policy.NoPolicy import org.scalafmt.util.TokenOps case class OptimalToken(token: Token, killOnFail: Boolean = false) /** * A Split is the whitespace between two non-whitespace tokens. * * Consider a split to be an edge in a search graph and [[FormatToken]] * are the nodes. * * @param modification Is this a space, no space, newline or 2 newlines? * @param cost How good is this output? Lower is better. * @param indents Does this add indentation? * @param policy How does this split affect other later splits? * @param penalty Does this split overflow the column limit? * @param line For debugging, to retrace from which case in [[Router]] * this split originates. * */ case class Split( modification: Modification, cost: Int, ignoreIf: Boolean = false, indents: Vector[Indent[Length]] = Vector.empty[Indent[Length]], policy: Policy = NoPolicy, penalty: Boolean = false, optimalAt: Option[OptimalToken] = None)(implicit val line: sourcecode.Line) { import TokenOps._ def adapt(formatToken: FormatToken): Split = modification match { case n: NewlineT if !n.noIndent && rhsIsCommentedOut(formatToken) => copy(modification = NewlineT(n.isDouble, noIndent = true)) case _ => this } val indentation = indents .map(_.length match { case Num(x) => x.toString case x => x.toString }) .mkString("[", ", ", "]") def length: Int = modification match { case m if m.isNewline => 0 case NoSplit => 0 case Space => 1 case Provided(code) => val firstLine = code.indexOf("\\n") if (firstLine == -1) code.length else firstLine } def withOptimalToken(token: Option[Token]): Split = token match { case Some(token) => withOptimalToken(token) case _ => this } def withOptimalToken(token: Token, killOnFail: Boolean = false): Split = { require(optimalAt.isEmpty) new Split(modification, cost, ignoreIf, indents, policy, true, Some(OptimalToken(token, killOnFail)))(line) } def withPolicy(newPolicy: Policy): Split = { val update = if (policy == NoPolicy) newPolicy else throw new UnsupportedOperationException("Can't have two policies yet.") new Split(modification, cost, ignoreIf, indents, update, true, optimalAt)( line) } def withPenalty(penalty: Int): Split = new Split(modification, cost + penalty, ignoreIf, indents, policy, true, optimalAt)(line) def withIndent(length: Length, expire: Token, expiresOn: ExpiresOn): Split = { length match { case Num(0) => this case _ => new Split(modification, cost, ignoreIf, Indent(length, expire, expiresOn) +: indents, policy, penalty, optimalAt)(line) } } def sameSplit(other: Split): Boolean = this.modification == other.modification && this.line.value == other.line.value && this.cost == other.cost override def toString = s"""$modification:${line.value}(cost=$cost, indents=$indentation, $policy)""" }
Daxten/scalafmt
core/src/main/scala/org/scalafmt/internal/Split.scala
Scala
apache-2.0
3,418
package org.iainhull.resttest.driver import com.sun.jersey.api.client.Client import com.sun.jersey.api.client.ClientResponse import com.sun.jersey.api.client.WebResource import org.iainhull.resttest.Api import org.iainhull.resttest.TestDriver import scala.collection.JavaConverters /** * Provides the Jersey httpClient implementation (as a trait to support * mixing in). */ trait Jersey extends Api { import Jersey.Impl implicit val httpClient: HttpClient = { request => val response = Impl.createClientResponse(request) Response(response.getStatus, Impl.headers(response), Some(response.getEntity(classOf[String]))) } } /** * Provides the Jersey httpClient implementation (as an object to support * straight import). */ object Jersey extends Jersey { private object Impl { val jersey = Client.create() def createClientResponse(request: Request): ClientResponse = { val builder = addRequestHeaders(request.headers, jersey.resource(request.url).getRequestBuilder) for (b <- request.body) { builder.entity(b) } request.method match { case GET => builder.get(classOf[ClientResponse]) case POST => builder.post(classOf[ClientResponse]) case PUT => builder.put(classOf[ClientResponse]) case DELETE => builder.delete(classOf[ClientResponse]) case HEAD => builder.method("HEAD", classOf[ClientResponse]) case PATCH => builder.method("PATCH", classOf[ClientResponse]) } } def addRequestHeaders(headers: Map[String, List[String]], builder: WebResource#Builder): WebResource#Builder = { def forAllNames(names: List[String], b: WebResource#Builder): WebResource#Builder = { names match { case h :: t => forAllNames(t, forAllValues(h, headers(h), b)) case Nil => b } } def forAllValues(name: String, values: List[String], b: WebResource#Builder): WebResource#Builder = { values match { case h :: t => forAllValues(name, t, b.header(name, h)) case Nil => b } } forAllNames(headers.keys.toList, builder) } def headers(response: ClientResponse): Map[String, List[String]] = { import JavaConverters._ response.getHeaders.asScala.toMap.map { case (k, v) => (k, v.asScala.toList) } } } } /** * The JerseySystemTestDriver can be mixed into Rest Test Suites to execute * then with Jersey. Suites must provide the baseUrl from which all test * paths are relative. */ trait JerseySystemTestDriver extends TestDriver with Jersey { override implicit def defBuilder = RequestBuilder.emptyBuilder withUrl baseUrl /** * Implements must specify the baseUrl from which all test paths are relative. */ def baseUrl: String }
IainHull/resttest
src/main/scala/org/iainhull/resttest/driver/Jersey.scala
Scala
apache-2.0
2,799
package uk.co.turingatemyhamster.shortbol.pragma import java.io.IOException import org.scalajs.dom.raw.XMLHttpRequest import scalaz._ import scalaz.Scalaz._ /** * * * @author Matthew Pocock */ object Platform { val cache = scala.collection.mutable.Map.empty[String, Throwable \\/ String] def slurp(url: String): Throwable \\/ String = cache.getOrElseUpdate(url, { val xmlHttp = new XMLHttpRequest println("Made request") try { xmlHttp.open("GET", url, false) println("Opened connection") xmlHttp.send(null) println("Sent null") if(xmlHttp.status == 200) { println("Returning response text") xmlHttp.responseText.right } else { println("Bad status. Raising exception.") (new IOException(s"Failed to slurp $url with status ${xmlHttp.status}")).left } } catch { case t : Throwable => println("Caught exception - raising one") (new IOException(s"Failed to slurp $url", t)).left } }) }
drdozer/shortbol
shortbol/core/js/src/main/scala/uk/co/turingatemyhamster/shortbol/pragma/Platform.scala
Scala
apache-2.0
1,027
package com.softwaremill.quicklens import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers case class Named(name: String) case class Aged(age: Int) case class Eithers(e: Either[Named, Aged]) case class MoreEithers(e1: Either[Eithers, MoreEithers], e2: Either[Eithers, MoreEithers]) class ModifyEitherTest extends AnyFlatSpec with Matchers { it should "modify a single-nested left case class field" in { modify( Eithers(Left(Named("boo"))) )(_.e.eachLeft.name).setTo("moo") should be( Eithers(Left(Named("moo"))) ) } it should "modify a single-nested left case class field (pimped)" in { Eithers(Left(Named("boo"))) .modify(_.e.eachLeft.name) .setTo("moo") should be( Eithers(Left(Named("moo"))) ) } it should "modify a single-nested right case class field" in { modify( Eithers(Right(Aged(23))) )(_.e.eachRight.age).setTo(32) should be( Eithers(Right(Aged(32))) ) } it should "modify a single-nested right case class field (pimped)" in { Eithers(Right(Aged(23))) .modify(_.e.eachRight.age) .setTo(32) should be( Eithers(Right(Aged(32))) ) } it should "modify multiple deeply-nested either case class fields" in { modify( MoreEithers( e1 = Right( MoreEithers( e1 = Left(Eithers(Right(Aged(23)))), e2 = Left(Eithers(Left(Named("boo")))) ) ), e2 = Left(Eithers(Left(Named("boo")))) ) )(_.e1.eachRight.e2.eachLeft.e.eachLeft.name) .using(_.toUpperCase) should be( MoreEithers( e1 = Right( MoreEithers( e1 = Left(Eithers(Right(Aged(23)))), e2 = Left(Eithers(Left(Named("BOO")))) ) ), e2 = Left(Eithers(Left(Named("boo")))) ) ) } it should "not modify left case class field if it is right" in { modify( Eithers(Right(Aged(23))) )(_.e.eachLeft.name).setTo("moo") should be( Eithers(Right(Aged(23))) ) } it should "not modify right case class field if it is left" in { modify( Eithers(Left(Named("boo"))) )(_.e.eachRight.age).setTo(33) should be( Eithers(Left(Named("boo"))) ) } it should "allow .eachLeft at then end" in { modify(Left("boo"): Either[String, Int])(_.eachLeft) .using(_.toUpperCase) should be(Left("BOO")) } it should "allow .eachRight at then end" in { modify(Right(23): Either[String, Int])(_.eachRight).using(_ + 3) should be(Right(26)) } }
adamw/quicklens
quicklens/src/test/scala/com/softwaremill/quicklens/ModifyEitherTest.scala
Scala
apache-2.0
2,576
package nest.sparkle.time.server import java.io.{File, FileInputStream, FileOutputStream} import java.nio.file.Path import com.typesafe.config.Config import scala.collection.JavaConverters._ import scala.concurrent.Future import scala.concurrent.duration._ import spray.http.HttpHeaders.{RawHeader, _} import spray.http._ import spray.http.parser.HttpParser import spray.io.CommandWrapper import akka.actor._ import org.jvnet.mimepull.{MIMEMessage, MIMEPart} import nest.sparkle.loader.SingleFileLoader import nest.sparkle.store.WriteableStore import nest.sparkle.util.{Log, ConfigUtil} // adapted from spray.io example code /** spray.io handler for chunked file upload into the store. Create this actor to handle the upload * of a single file after the the ChunkedRequestStart message has been received by the io layer. */ class FileUploadHandler(rootConfig:Config, store:WriteableStore, batchSize:Int, client: ActorRef, start: ChunkedRequestStart) extends Actor with Log { import start.request._ client ! CommandWrapper(SetRequestTimeout(Duration.Inf)) // cancel timeout, uploading is slow val uploadedMime = File.createTempFile("chunked-receive", ".tmp", new File("/tmp")) uploadedMime.deleteOnExit() val mimeFileStream = new FileOutputStream(uploadedMime) val Some(HttpHeaders.`Content-Type`(ContentType(multipart: MultipartMediaType, _))) = header[HttpHeaders.`Content-Type`] val boundary = multipart.parameters("boundary") import context.dispatcher val loader = new SingleFileLoader(ConfigUtil.configForSparkle(rootConfig), store, batchSize) log.info(s"Got start of chunked request $method $uri with multipart boundary '$boundary' writing to $uploadedMime") var bytesWritten = 0L def receive = { case c: MessageChunk => log.debug(s"Got ${c.data.length} bytes of chunked request $method $uri") mimeFileStream.write(c.data.toByteArray) bytesWritten += c.data.length case e: ChunkedMessageEnd => log.info(s"Got end of chunked request $method $uri") mimeFileStream.close() val files = messageToFiles(uploadedMime) files.foreach { file => loadFileIntoStore(file.toPath) } client ! HttpResponse(status = 200, headers = List(`Access-Control-Allow-Origin`(AllOrigins)), // TODO fixme entity = "") client ! CommandWrapper(SetRequestTimeout(2.seconds)) // reset timeout to original value uploadedMime.delete() context.stop(self) } def messageToFiles(mimeFile:File): Seq[File] = { val message = new MIMEMessage(new FileInputStream(mimeFile), boundary) val parts = message.getAttachments.asScala.toVector parts.map { part => val fileName = fileNameForPart(part).getOrElse("unknown") val file = new File(s"/tmp/$fileName") log.debug("writing uploaded file $file") part.moveTo(file) file.deleteOnExit() file } } def loadFileIntoStore(path:Path): Future[Unit]= { loader.loadFile(path, path.toString, path.getParent()) } def fileNameForPart(part: MIMEPart): Option[String] = for { dispHeader <- part.getHeader("Content-Disposition").asScala.toSeq.lift(0) Right(disp: `Content-Disposition`) = HttpParser.parseHeader(RawHeader("Content-Disposition", dispHeader)) name <- disp.parameters.get("filename") } yield name }
mighdoll/sparkle
protocol/src/main/scala/nest/sparkle/time/server/FileUploadHandler.scala
Scala
apache-2.0
3,395
package code package snippet import scala.xml.{NodeSeq, Text} import net.liftweb.util._ import net.liftweb.common._ import java.util.Date import code.lib._ import Helpers._ import net.liftweb.http._ import js._ class HelloWorld { lazy val date: Box[Date] = DependencyFactory.inject[Date] // inject the date // replace the contents of the element with id "time" with the date def howdy = "#time *" #> date.map(_.toString) /* lazy val date: Date = DependencyFactory.time.vend // create the date via factory def howdy = "#time *" #> date.toString */ def render = { "@ajax-click [onclick]" #> SHtml.ajaxInvoke(() => { println("Ajax click") // JE.JsRaw("failed();").cmd }) } }
saikitanabe/lidtest
src/main/scala/code/snippet/HelloWorld.scala
Scala
apache-2.0
721
package play.api.cache.redis.connector import scala.concurrent.Future import scala.concurrent.duration.Duration import scala.reflect.ClassTag /** * Internal non-blocking Redis API implementing REDIS protocol * * Subset of REDIS commands, basic commands. * * @see https://redis.io/commands */ private[redis] trait CoreCommands { /** * Retrieve a value from the cache. * * @param key cache storage key * @return stored record, Some if exists, otherwise None */ def get[T: ClassTag](key: String): Future[Option[T]] /** * Retrieve a values from the cache. * * @param keys cache storage key * @return stored record, Some if exists, otherwise None */ def mGet[T: ClassTag](keys: String*): Future[Seq[Option[T]]] /** * Determines whether value exists in cache. * * @param key cache storage key * @return record existence, true if exists, otherwise false */ def exists(key: String): Future[Boolean] /** * Retrieves all keys matching the given pattern. This method invokes KEYS command * * '''Warning:''' complexity is O(n) where n are all keys in the database * * @param pattern valid KEYS pattern with wildcards * @return list of matching keys */ def matching(pattern: String): Future[Seq[String]] /** * Set a value into the cache. Expiration time in seconds (0 second means eternity). * * @param key cache storage key * @param value value to store * @param expiration record duration in seconds * @param ifNotExists set only if the key does not exist * @return promise */ def set(key: String, value: Any, expiration: Duration = Duration.Inf, ifNotExists: Boolean = false): Future[Boolean] /** * Set a value into the cache. Expiration time is the eternity. * * @param keyValues cache storage key-value pairs to store * @return promise */ def mSet(keyValues: (String, Any)*): Future[Unit] /** * Set a value into the cache. Expiration time is the eternity. * It either set all values or it sets none if any of them already exists. * * @param keyValues cache storage key-value pairs to store * @return promise */ def mSetIfNotExist(keyValues: (String, Any)*): Future[Boolean] /** * refreshes expiration time on a given key, useful, e.g., when we want to refresh session duration * * @param key cache storage key * @param expiration new expiration in seconds * @return promise */ def expire(key: String, expiration: Duration): Future[Unit] /** * returns the remaining time to live of a key that has an expire set, * useful, e.g., when we want to check remaining session duration * * @param key cache storage key * @return the remaining time to live of a key in milliseconds */ def expiresIn(key: String): Future[Option[Duration]] /** * Removes all keys in arguments. The other remove methods are for syntax sugar * * @param keys cache storage keys * @return promise */ def remove(keys: String*): Future[Unit] /** * Remove all keys in cache * * @return promise */ def invalidate(): Future[Unit] /** * Sends PING command to REDIS and expects PONG in return * * @return promise */ def ping(): Future[Unit] /** * Increments the stored string value representing 10-based signed integer * by given value. * * @param key cache storage key * @param by size of increment * @return the value after the increment */ def increment(key: String, by: Long): Future[Long] /** * If key already exists and is a string, this command appends the value at the * end of the string. If key does not exist it is created and set as an empty string, * so APPEND will be similar to SET in this special case. * * @param key cache storage key * @param value value to be appended * @return number of characters of current value */ def append(key: String, value: String): Future[Long] } /** * Internal non-blocking Redis API implementing REDIS protocol * * Subset of REDIS commands, Hash-related commands. * * @see https://redis.io/commands */ private[redis] trait HashCommands { /** * Removes the specified fields from the hash stored at key. Specified fields that do not exist within this * hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0. * * Time complexity: O(N) where N is the number of fields to be removed. * * @param key cache storage key * @param field fields to be removed * @return the number of fields that were removed from the hash, not including specified but non existing fields. */ def hashRemove(key: String, field: String*): Future[Long] /** * Returns if field is an existing field in the hash stored at key. * * Time complexity: O(1) * * @param key cache storage key * @param field tested field name * @return true if the field exists, false otherwise */ def hashExists(key: String, field: String): Future[Boolean] /** * Returns the value associated with field in the hash stored at key. * * Time complexity: O(1) * * @param key cache storage key * @param field accessed field * @return Some value if the field exists, otherwise None */ def hashGet[T: ClassTag](key: String, field: String): Future[Option[T]] /** * Returns the values associated with fields in the hash stored at given keys. * * Time complexity: O(n), where n is number of fields * * @param key cache storage key * @param fields accessed fields to get * @return Some value if the field exists, otherwise None */ def hashGet[T: ClassTag](key: String, fields: Seq[String]): Future[Seq[Option[T]]] /** * Returns all fields and values of the hash stored at key. In the returned value, every field name is followed * by its value, so the length of the reply is twice the size of the hash. * * Time complexity: O(N) where N is the size of the hash. * * @param key cache storage key * @tparam T expected type of the elements * @return the stored map */ def hashGetAll[T: ClassTag](key: String): Future[Map[String, T]] /** * Increment a value at the given key in the map * * @param key cache storage key * @param field key * @param incrementBy increment by this * @return value after incrementation */ def hashIncrement(key: String, field: String, incrementBy: Long): Future[Long] /** * Returns the number of fields contained in the hash stored at key. * * Time complexity: O(1) * * @param key cache storage key * @return size of the hash */ def hashSize(key: String): Future[Long] /** * Returns all field names in the hash stored at key. * * Time complexity: O(N) where N is the size of the hash. * * @param key cache storage key * @return set of field names */ def hashKeys(key: String): Future[Set[String]] /** * Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten. * * Time complexity: O(1) * * @param key cache storage key * @param field field to be set * @param value value to be set * @return true if the field was newly set, false if was updated */ def hashSet(key: String, field: String, value: Any): Future[Boolean] /** * Returns all values in the hash stored at key. * * Time complexity: O(N) where N is the size of the hash. * * @param key cache storage key * @return all values in the hash object */ def hashValues[T: ClassTag](key: String): Future[Set[T]] } /** * Internal non-blocking Redis API implementing REDIS protocol * * Subset of REDIS commands, List-related commands. * * @see https://redis.io/commands */ private[redis] trait ListCommands { /** * Insert (LPUSH) all the specified values at the head of the list stored at key. * If key does not exist, it is created as empty list before performing the push operations. * When key holds a value that is not a list, an error is returned. * * Time complexity: O(1) * * @param key cache storage key * @param value prepended values * @return new length of the list */ def listPrepend(key: String, value: Any*): Future[Long] /** * Insert (RPUSH) all the specified values at the tail of the list stored at key. If key * does not exist, it is created as empty list before performing the push operation. * When key holds a value that is not a list, an error is returned. * * Time complexity: O(1) * * @param key cache storage key * @param value appended values * @return new length of the list */ def listAppend(key: String, value: Any*): Future[Long] /** * Returns the length of the list stored at key (LLEN). If key does not exist, it is interpreted as an empty * list and 0 is returned. An error is returned when the value stored at key is not a list. * * Time complexity: O(1) * * @param key cache storage key * @return length of the list */ def listSize(key: String): Future[Long] /** * Inserts value in the list stored at key either before or after the reference value pivot. * When key does not exist, it is considered an empty list and no operation is performed. * An error is returned when key exists but does not hold a list value. * * Time complexity: O(N) where N is the number of elements to traverse before seeing the value pivot. * * @param key cache storage key * @param pivot value used as markup * @param value value to be inserted * @return the length of the list after the insert operation, or None when the value pivot was not found. */ def listInsert(key: String, pivot: Any, value: Any): Future[Option[Long]] /** * Sets the list element at index to value. For more information on the index argument, see LINDEX. An error is * returned for out of range indexes. * * Time complexity: O(N) where N is the length of the list. Setting either the first or the last element * of the list is O(1). * * @param key cache storage key * @param position position to be overwritten * @param value value to be set * @return promise */ def listSetAt(key: String, position: Int, value: Any): Future[Unit] /** * Removes and returns the first element of the list stored at key (LPOP). * * Time complexity: O(1) * * @param key cache storage key * @tparam T type of the value * @return head of the list, if existed */ def listHeadPop[T: ClassTag](key: String): Future[Option[T]] /** * Returns the specified elements of the list stored at key (LRANGE). The offsets start and stop are zero-based * indexes, with 0 being the first element of the list (the head of the list), 1 being the next element and so on. * * These offsets can also be negative numbers indicating offsets starting at the end of the list. For example, * -1 is the last element of the list, -2 the penultimate, and so on. * * Time complexity: O(S+N) where S is the distance of start offset from HEAD for small lists, from nearest end * (HEAD or TAIL) for large lists; and N is the number of elements in the specified range. * * @param key cache storage key * @param start initial index of the subset * @param end last index of the subset (included) * @tparam T type of the values * @return subset of existing set */ def listSlice[T: ClassTag](key: String, start: Int, end: Int): Future[Seq[T]] /** * Removes (LREM) the first count occurrences of elements equal to value from the list stored at key. The count * argument influences the operation in the following ways: * count > 0: Remove elements equal to value moving from head to tail. * count < 0: Remove elements equal to value moving from tail to head. * count = 0: Remove all elements equal to value. * * @param key cache storage key * @param value value to be removed * @param count number of elements to be removed * @return number of removed elements */ def listRemove(key: String, value: Any, count: Int): Future[Long] /** * Trim an existing list so that it will contain only the specified range of elements specified. Both start and stop * are zero-based indexes, where 0 is the first element of the list (the head), 1 the next element and so on. * * For example: LTRIM foobar 0 2 will modify the list stored at foobar so that only the first three elements of * the list will remain. start and end can also be negative numbers indicating offsets from the end of the list, * where -1 is the last element of the list, -2 the penultimate element and so on. * * Time complexity: O(N) where N is the number of elements to be removed by the operation. * * @param key cache storage key * @param start initial index of preserved subset * @param end last index of preserved subset (included) * @return promise */ def listTrim(key: String, start: Int, end: Int): Future[Unit] } /** * Internal non-blocking Redis API implementing REDIS protocol * * Subset of REDIS commands, unordered Set-related commands. * * @see https://redis.io/commands */ private[redis] trait SetCommands { /** * Add the specified members to the set stored at key. Specified members that are already a member of this set * are ignored. If key does not exist, a new set is created before adding the specified members. * * An error is returned when the value stored at key is not a set. * * @note Time complexity: O(1) for each element added, so O(N) to add N elements when the command is called * with multiple arguments. * @param key cache storage key * @param value values to be added * @return number of inserted elements ignoring already existing */ def setAdd(key: String, value: Any*): Future[Long] /** * Returns the set cardinality (number of elements) of the set stored at key. * * Time complexity: O(1) * * @param key cache storage key * @return the cardinality (number of elements) of the set, or 0 if key does not exist. */ def setSize(key: String): Future[Long] /** * Returns all the members of the set value stored at key. * * This has the same effect as running SINTER with one argument key. * * Time complexity: O(N) where N is the set cardinality. * * @param key cache storage key * @tparam T expected type of the elements * @return the subset */ def setMembers[T: ClassTag](key: String): Future[Set[T]] /** * Returns if member is a member of the set stored at key. * * Time complexity: O(1) * * @param key cache storage key * @param value tested element * @return true if the element exists in the set, otherwise false */ def setIsMember(key: String, value: Any): Future[Boolean] /** * Remove the specified members from the set stored at key. Specified members that are not a member of this set * are ignored. If key does not exist, it is treated as an empty set and this command returns 0. * * An error is returned when the value stored at key is not a set. * * Time complexity: O(N) where N is the number of members to be removed. * * @param key cache storage key * @param value values to be removed * @return total number of removed values, non existing are ignored */ def setRemove(key: String, value: Any*): Future[Long] } /** * Internal non-blocking Redis API implementing REDIS protocol * * Subset of REDIS commands, sorted set related commands. * * @see https://redis.io/commands */ private[redis] trait SortedSetCommands { /** * Adds all the specified members with the specified scores to the sorted set stored at key. * It is possible to specify multiple score / member pairs. If a specified member is already * a member of the sorted set, the score is updated and the element reinserted at the right * position to ensure the correct ordering. * * If key does not exist, a new sorted set with the specified members as sole members is created, * like if the sorted set was empty. If the key exists but does not hold a sorted set, an error * is returned. * * @note Time complexity: O(log(N)) for each item added, where N is the number of elements in the sorted set. * @param key cache storage key * @param scoreValues values and corresponding scores to be added * @return number of inserted elements ignoring already existing */ def sortedSetAdd(key: String, scoreValues: (Double, Any)*): Future[Long] /** * Returns the sorted set cardinality (number of elements) of the sorted set stored at key. * * Time complexity: O(1) * * @param key cache storage key * @return the cardinality (number of elements) of the set, or 0 if key does not exist. */ def sortedSetSize(key: String): Future[Long] /** * Returns the score of member in the sorted set at key. * * If member does not exist in the sorted set, or key does not exist, nil is returned. * * Time complexity: O(1) * * @param key cache storage key * @param value tested element * @return the score of member (a double precision floating point number). */ def sortedSetScore(key: String, value: Any): Future[Option[Double]] /** * Removes the specified members from the sorted set stored at key. Non existing members are ignored. * * An error is returned when key exists and does not hold a sorted set. * * Time complexity: O(M*log(N)) with N being the number of elements in the sorted set and M the number of elements to be removed. * * @param key cache storage key * @param value values to be removed * @return total number of removed values, non existing are ignored */ def sortedSetRemove(key: String, value: Any*): Future[Long] /** * Returns the specified range of elements in the sorted set stored at key. * * An error is returned when key exists and does not hold a sorted set. * @param key cache storage key * @param start the start index of the range * @param stop the stop index of the range * @note The start and stop arguments represent zero-based indexes, where 0 is the first element, * 1 is the next element, and so on. These arguments specify an inclusive range. * @return list of elements in the specified range */ def sortedSetRange[T: ClassTag](key: String, start: Long, stop: Long): Future[Seq[T]] /** * Returns the specified range of elements in the sorted set stored at key. * The elements are considered to be ordered from the highest to the lowest score. * Descending lexicographical order is used for elements with equal score. * * @param key cache storage key * @param start the start index of the range * @param stop the stop index of the range * @note Apart from the reversed ordering, the zrevRange is similar to zrange. * @return list of elements in the specified range */ def sortedSetReverseRange[T: ClassTag](key: String, start: Long, stop: Long): Future[Seq[T]] } /** * Internal non-blocking Redis API implementing REDIS protocol * * @see https://redis.io/commands */ trait RedisConnector extends AnyRef with CoreCommands with ListCommands with SetCommands with HashCommands with SortedSetCommands
KarelCemus/play-redis
src/main/scala/play/api/cache/redis/connector/RedisConnector.scala
Scala
mpl-2.0
19,919
/* * Copyright (c) 2010 Pedro Matiello <pmatiello@gmail.com> * * Integration tests. * * These tests aim for checking the interaction between different parts of the framework. */ package pistache.integration import pistache.runner.threaded.ThreadedRunner import org.scalatest.Spec import org.scalatest.matchers.MustMatchers import org.scalatest.junit.JUnitRunner import org.junit.runner.RunWith import java.util.Random @RunWith(classOf[JUnitRunner]) class IntegrationTests extends Spec with MustMatchers { val random = new Random() def randomList(size:Int):List[Int] = if (size > 0) random.nextInt(10000) :: randomList(size-1) else Nil describe ("ThreadedRunner tests") { it ("Actions, concatenation and recursion") { val factorialCalculator = new Factorial(10) new ThreadedRunner(factorialCalculator.agent).start factorialCalculator.result must equal (10*9*8*7*6*5*4*3*2*1) } it ("Message passing and parallel composition") { val PingPong = new PingPong(1000) new ThreadedRunner(PingPong.agent).start PingPong.result must equal (List.range(0,1000)) } it ("Message passing and channel locking") { val ProducerConsumer = new ProducerConsumer(500000) new ThreadedRunner(ProducerConsumer.agent).start } it ("Message passing and complementary sums") { val ProducerConsumer = new ProducerConsumerWithComplementarySums(500000) new ThreadedRunner(ProducerConsumer.agent).start } it ("Message passing and input guarded sums") { val ProducerConsumer = new ProducerConsumerWithInputSums(500000) new ThreadedRunner(ProducerConsumer.agent).start } it ("Message passing and output guarded sums") { val ProducerConsumer = new ProducerConsumerWithOutputSums(500000) new ThreadedRunner(ProducerConsumer.agent).start } it ("Agents with arguments and massive threading") { val unsortedList = randomList(300) val qsort = new Quicksort(unsortedList) new ThreadedRunner(qsort.agent).start qsort.result.value must equal (unsortedList.sortWith(_ < _)) } it ("Deep recursion by concatenation") { val list = 1 to 100000 toList val summation = new Summation(list) new ThreadedRunner(summation.agent).start summation.sum must equal (list.reduceLeft(_+_)) } it ("Deep recursion by composition") { val list = 1 to 10000 toList val summation = new CompositionSummation(list) new ThreadedRunner(summation.agent).start summation.sum must equal (list.reduceLeft(_+_)) } } }
pmatiello/pistache
test/pistache/integration/IntegrationTests.scala
Scala
mit
2,511
package rpm4s.data case class PayloadDigest(checksum: Checksum)
lucidd/rpm4s
shared/src/main/scala/rpm4s/data/PayloadDigest.scala
Scala
mit
64
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package com.lightbend.lagom.internal.client import akka.discovery.Lookup import com.typesafe.config.ConfigFactory import org.scalatest.Matchers import org.scalatest.WordSpec class ServiceNameMapperSpec extends WordSpec with Matchers { private val defaultConfig = ConfigFactory.defaultReference().getConfig("lagom.akka.discovery") private val parser = new ServiceNameMapper(defaultConfig) val defaultPortName = Some("http") val defaultProtocol = Some("tcp") val defaultScheme = Some("http") private def createParser(config: String) = new ServiceNameMapper(ConfigFactory.parseString(config).withFallback(defaultConfig)) "The ServiceNameMapper" should { // ------------------------------------------------------------------------------ // Assert SRV lookups "parse an unqualified SRV lookup" in { val lookup = parser.mapLookupQuery("_fooname._fooprotocol.myservice").lookup lookup shouldBe Lookup("myservice", Some("fooname"), Some("fooprotocol")) } "parse a fully-qualified SRV lookup" in { val lookup = parser.mapLookupQuery("_fooname._fooprotocol.myservice.mynamespace.svc.cluster.local").lookup lookup shouldBe Lookup("myservice.mynamespace.svc.cluster.local", Some("fooname"), Some("fooprotocol")) } // ------------------------------------------------------------------------------ // Assert simple Service Name lookup "parse an unqualified service name" in { val lookup = parser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", defaultPortName, defaultProtocol) } "parse an fully-qualified service name" in { val lookup = parser.mapLookupQuery("myservice.mynamespace.svc.cluster.local").lookup lookup shouldBe Lookup("myservice.mynamespace.svc.cluster.local", defaultPortName, defaultProtocol) } // ------------------------------------------------------------------------------ // Assert blank defaults "return a DNS A lookup if defaults.port-name and defaults.port-protocol are 'blank'" in { val customParser = createParser("""{ |defaults.port-name = "" |defaults.port-protocol = "" |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", None, None) } "return a DNS A lookup if defaults.port-name and defaults.port-protocol are 'null'" in { val customParser = createParser("""{ |defaults.port-name = null |defaults.port-protocol = null |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", None, None) } "not include default port name if defaults.port-name is 'blank'" in { val customParser = createParser("""defaults.port-name = "" """) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", None, defaultProtocol) } "not include default port name if defaults.port-name is 'null'" in { val customParser = createParser("""defaults.port-name = null """) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", None, defaultProtocol) } "not include default port protocol if defaults.port-protocol is 'blank'" in { val customParser = createParser("""defaults.port-protocol = "" """) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", defaultPortName, None) } "not include default port protocol if defaults.port-protocol is 'null'" in { val customParser = createParser("""defaults.port-protocol = null """) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", defaultPortName, None) } // ------------------------------------------------------------------------------ // Assert custom mappings "return SRV lookup for a mapped service when defaults are not overwritten" in { val customParser = createParser("service-name-mappings.myservice.lookup = mappedmyservice") val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("mappedmyservice", defaultPortName, defaultProtocol) } "return a DNS A lookup for a mapped service when defaults are overwritten to 'null'" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = mappedmyservice | port-name = null | port-protocol = null |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("mappedmyservice", None, None) } "return a DNS A lookup for a mapped service when defaults are overwritten to 'blank'" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = mappedmyservice | port-name = "" | port-protocol = "" |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("mappedmyservice", None, None) } "return SRV lookup for a mapped service using SRV format" in { val customParser = createParser("service-name-mappings.myservice.lookup = _remoting._udp.mappedmyservice") val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("mappedmyservice", Some("remoting"), Some("udp")) } "honour SRV format in service name instead of overwritten port-name and port-protocol" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = _remoting._udp.mappedmyservice | port-name = some-port | port-protocol = tcp |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("mappedmyservice", Some("remoting"), Some("udp")) } "return SRV lookup for a mapped service without configured 'lookup' field" in { val customParser = createParser(""" |service-name-mappings.myservice { | port-name = remoting | port-protocol = udp |} """.stripMargin) val lookup = customParser.mapLookupQuery("myservice").lookup lookup shouldBe Lookup("myservice", Some("remoting"), Some("udp")) } // ------------------------------------------------------------------------------ // Assert Schema mapping "return a default scheme if not specified" in { val serviceLookup = parser.mapLookupQuery("myservice") serviceLookup.scheme should be(defaultScheme) } "not include default scheme if defaults.scheme is 'blank'" in { val customParser = createParser("""defaults.scheme = "" """) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(None) } "not include default scheme if defaults.scheme is 'null'" in { val customParser = createParser("""defaults.scheme = null """) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(None) } "not include scheme if service-name-mappings.myservice.scheme is 'blank'" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = _remoting._udp.mappedmyservice | scheme = "" |} """.stripMargin) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(None) } "not include scheme if service-name-mappings.myservice.scheme is 'null'" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = _remoting._udp.mappedmyservice | scheme = null |} """.stripMargin) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(None) } "return a mapped schema for a mapped SVR" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = _remoting._udp.mappedmyservice | scheme = bar |} """.stripMargin) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(Some("bar")) } "return a default schema for a mapped SVR" in { val customParser = createParser(""" |service-name-mappings.myservice { | lookup = _remoting._udp.mappedmyservice |} """.stripMargin) val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(defaultScheme) } "return a mapped scheme" in { val customParser = createParser("service-name-mappings.myservice.scheme = foo") val serviceLookup = customParser.mapLookupQuery("myservice") serviceLookup.scheme should be(Some("foo")) } } }
lagom/lagom
akka-service-locator/core/src/test/scala/com/lightbend/lagom/internal/client/ServiceNameMapperSpec.scala
Scala
apache-2.0
10,477
object O { val x: Function1[String, String] = a => a val x2: Function1[String, String] = a => "1" }
yusuke2255/dotty
tests/pos/i480.scala
Scala
bsd-3-clause
104
/** * This file is part of the "eidolon" project. * * Unless required by applicable law or agreed to in writing, software * distributed under the LICENSE is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import sbt._ /** * Main Dependencies File * * @author Elliot Wright <elliot@elliotwright.co> */ object Dependencies { val repositories = Seq( "Akka Snapshot Repository" at "http://repo.akka.io/snapshots/", "spray repo" at "http://repo.spray.io", "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" ) def compile(deps: ModuleID*): Seq[ModuleID] = deps.map(_ % "compile") def container(deps: ModuleID*): Seq[ModuleID] = deps.map(_ % "container") def provided(deps: ModuleID*): Seq[ModuleID] = deps.map(_ % "provided") def runtime(deps: ModuleID*): Seq[ModuleID] = deps.map(_ % "runtime") def test(deps: ModuleID*): Seq[ModuleID] = deps.map(_ % "test") val akkaVersion = "2.3.11" val sprayVersion = "1.3.3" val akkaActor = "com.typesafe.akka" %% "akka-actor" % akkaVersion val scalaAsync = "org.scala-lang.modules" %% "scala-async" % "0.9.3" val scalaTest = "org.scalatest" %% "scalatest" % "2.2.4" val sprayCan = "io.spray" %% "spray-can" % sprayVersion }
eidolon/eidolon-scala
project/Dependencies.scala
Scala
mit
1,499
/* * Scala (https://www.scala-lang.org) * * Copyright EPFL and Lightbend, Inc. * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package scala.tools.nsc.interpreter import Results.{Result, Success} trait ExprTyper { val repl: IMain import repl._ import global.{ phase, Symbol, Type, exitingTyper, NoSymbol, NoType, NoPrefix, TypeRef, WildcardType } import naming.freshInternalVarName import global.definitions.{ MaxFunctionArity, NothingTpe } private def doInterpret(code: String): Result = { // interpret/interpretSynthetic may change the phase, which would have unintended effects on types. val savedPhase = phase try interpretSynthetic(code) finally phase = savedPhase } def symbolOfLine(code: String): Symbol = { def asExpr(): Symbol = { val name = freshInternalVarName() // Typing it with a lazy val would give us the right type, but runs // into compiler bugs with things like existentials, so we compile it // behind a def and strip the NullaryMethodType which wraps the expr. val line = "def " + name + " = " + code doInterpret(line) match { case Success => val sym0 = symbolOfTerm(name) // drop NullaryMethodType sym0.cloneSymbol setInfo exitingTyper(sym0.tpe_*.finalResultType) case _ => NoSymbol } } def asDefn(): Symbol = { val old = repl.definedSymbolList.toSet doInterpret(code) match { case Success => repl.definedSymbolList filterNot old match { case Nil => NoSymbol case sym :: Nil => sym case syms => NoSymbol.newOverloaded(NoPrefix, syms) } case _ => NoSymbol } } def asError(): Symbol = { doInterpret(code) NoSymbol } reporter.suppressOutput { asExpr() orElse asDefn() } orElse asError() } private var typeOfExpressionDepth = 0 def typeOfExpression(expr: String, silent: Boolean = true): Type = { if (typeOfExpressionDepth > 2) { // repldbg("Terminating typeOfExpression recursion for expression: " + expr) return NoType } typeOfExpressionDepth += 1 // Don't presently have a good way to suppress undesirable success output // while letting errors through, so it is first trying it silently: if there // is an error, and errors are desired, then it re-evaluates non-silently // to induce the error message. try reporter.suppressOutput(symbolOfLine(expr).tpe) match { case NoType if !silent => symbolOfLine(expr).tpe // generate error case tpe => tpe } finally typeOfExpressionDepth -= 1 } // Try typeString[Nothing], typeString[Nothing, Nothing], etc. def typeOfTypeString(typeString: String): Type = { val properTypeOpt = typeOfProperTypeString(typeString) def typeFromTypeString(n: Int): Option[Type] = { val ts = typeString + List.fill(n)("_root_.scala.Nothing").mkString("[", ", ", "]") val tpeOpt = typeOfProperTypeString(ts) tpeOpt map { // Type lambda is detected. Substitute Nothing with WildcardType. case TypeRef(pre, sym, args) if args.size != n => TypeRef(pre, sym, args map { case NothingTpe => WildcardType case t => t }) case TypeRef(pre, sym, args) => TypeRef(pre, sym, Nil) case tpe => tpe } } val typeOpt = (1 to MaxFunctionArity).foldLeft(properTypeOpt){ (acc, n: Int) => acc orElse typeFromTypeString(n) } typeOpt getOrElse NoType } // This only works for proper types. private[interpreter] def typeOfProperTypeString(typeString: String): Option[Type] = { def asProperType(): Option[Type] = { val name = freshInternalVarName() val line = s"def $name: $typeString = ???" doInterpret(line) match { case Success => val tpe0 = exitingTyper { symbolOfTerm(name).asMethod.returnType } Some(tpe0) case _ => None } } reporter.suppressOutput(asProperType()) } }
lrytz/scala
src/repl/scala/tools/nsc/interpreter/ExprTyper.scala
Scala
apache-2.0
4,288
package org.deepdive.inference import akka.actor._ import scala.sys.process._ import scala.util.{Success, Failure} /* Companion object for the Sampler actor. Use the props method to create a new Sampler */ object Sampler { def props = Props[Sampler] // Tells the Sampler to run inference case class Run(samplerCmd: String, samplerOptions: String, weightsFile: String, variablesFile: String, factorsFile: String, edgesFile: String, metaFile: String, outputDir: String) } /* Runs inferece on a dumped factor graph. */ class Sampler extends Actor with ActorLogging { override def preStart() = { log.info("starting") } def receive = { case Sampler.Run(samplerCmd, samplerOptions, weightsFile, variablesFile, factorsFile, edgesFile, metaFile, outputDir) => // Build the command val cmd = buildSamplerCmd(samplerCmd, samplerOptions, weightsFile, variablesFile, factorsFile, edgesFile, metaFile, outputDir) log.info(s"Executing: ${cmd.mkString(" ")}") // We run the process, get its exit value, and print its output to the log file val exitValue = cmd!(ProcessLogger( out => log.info(out), err => System.err.println(err) )) // Depending on the exit value we return success or throw an exception exitValue match { case 0 => sender ! Success() case _ => throw new RuntimeException("sampling failed (see error log for more details)") } } // Build the command to run the sampler def buildSamplerCmd(samplerCmd: String, samplerOptions: String, weightsFile: String, variablesFile: String, factorsFile: String, edgesFile: String, metaFile: String, outputDir: String) = { log.info(samplerCmd) samplerCmd.split(" ").toSeq ++ Seq( "-w", weightsFile, "-v", variablesFile, "-f", factorsFile, "-e", edgesFile, "-m", metaFile, "-o", outputDir) ++ samplerOptions.split(" ") } }
dennybritz/deepdive
src/main/scala/org/deepdive/inference/Sampler.scala
Scala
apache-2.0
1,943
package health import org.specs2.mutable._ import spray.testkit.Specs2RouteTest import spray.http._ import StatusCodes._ import scala.concurrent.Future class CheckerSpec extends Specification with Specs2RouteTest with Checker { sequential def actorRefFactory = system var rawEndpointsOption: Option[String] = None override def rawEndpoints: Option[String] = rawEndpointsOption var result: Future[HttpResponse] = Future.successful(HttpResponse(OK)) var observerdRequest: List[HttpRequest] = List.empty override def pipeline = (request: HttpRequest) => { observerdRequest = request :: observerdRequest result } "Checker" should { "say 200 if no endpoints are configured" in { set(None, OK) Get("/health") ~> sealRoute(checkRoute) ~> check { status === OK } } "say 200 if requests pass" in { set(Some("healthy,endpoints"), OK) Get("/health") ~> sealRoute(checkRoute) ~> check { status === OK } } "httpify the endpoints if not already present" in { set(Some("healthy,endpoints"), OK) Get("/health") ~> sealRoute(checkRoute) ~> check { observerdRequest.filter( !_.uri.toString().startsWith("http://")) should beEmpty } } "not httpify the endpoints if not already present" in { set(Some("http://healthy,http://endpoints"), OK) Get("/health") ~> sealRoute(checkRoute) ~> check { observerdRequest.filter( _.uri.toString().startsWith("http://http")) should beEmpty } } "say 500 if a request fails" in { set(Some("http://dev.null"), InternalServerError) Get("/health") ~> sealRoute(checkRoute) ~> check { status === InternalServerError } } } def set(rawEndpoints: Option[String], status: StatusCode) = { rawEndpointsOption = rawEndpoints result = Future.successful(HttpResponse(status)) } }
ExpatConnect/health
src/test/scala/health/CheckerSpec.scala
Scala
mit
1,910
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package helpers import scala.util.Random object RandomNino { var validPrefixes = "AE|AH|AK|AL|AM|AP|AR|AS|AT|AW|AX|AY|AZ|BA|BB|BE|BH|BK|BL|BM|BT|CA|CB|CE|CH|CK|CL|CR|EA|EB|EE|EH|EK|EL|EM|EP|ER|ES|ET|EW|EX|EY|EZ|GY|HA|HB|HE|HH|HK|HL|HM|HP|HR|HS|HT|HW|HX|HY|HZ|JA|JB|JC|JE|JG|JH|JJ|JK|JL|JM|JN|JP|JR|JS|JT|JW|JX|JY|JZ|KA|KB|KE|KH|KK|KL|KM|KP|KR|KS|KT|KW|KX|KY|KZ|LA|LB|LE|LH|LK|LL|LM|LP|LR|LS|LT|LW|LX|LY|LZ|MA|MW|MX|NA|NB|NE|NH|NL|NM|NP|NR|NS|NW|NX|NY|NZ|OA|OB|OE|OH|OK|OL|OM|OP|OR|OS|OX|PA|PB|PC|PE|PG|PH|PJ|PK|PL|PM|PN|PP|PR|PS|PT|PW|PX|PY|RA|RB|RE|RH|RK|RM|RP|RR|RS|RT|RW|RX|RY|RZ|SA|SB|SC|SE|SG|SH|SJ|SK|SL|SM|SN|SP|SR|SS|ST|SW|SX|SY|SZ|TA|TB|TE|TH|TK|TL|TM|TP|TR|TS|TT|TW|TX|TY|TZ|WA|WB|WE|WK|WL|WM|WP|YA|YB|YE|YH|YK|YL|YM|YP|YR|YS|YT|YW|YX|YY|YZ|ZA|ZB|ZE|ZH|ZK|ZL|ZM|ZP|ZR|ZS|ZT|ZW|ZX|ZY".split('|') val validSuffixes = "A|B|C|D".split('|') def generate : String ={ val prefix = validPrefixes(Random.nextInt(validPrefixes.length)) val number = Random.nextInt(1000000) val suffix = validSuffixes(Random.nextInt(validSuffixes.length)) f"$prefix$number%06d$suffix" } }
hmrc/gmp-frontend
test/helpers/RandomNino.scala
Scala
apache-2.0
1,706
package scalatags package generic import utest._ import TestUtil.strCheck class ExampleTests[Builder, Output <: FragT, FragT]( bundle: Bundle[Builder, Output, FragT]) extends TestSuite { val tests = TestSuite { 'manualImports - strCheck({ // bundle is scalatags.Text or scalatags.JsDom import bundle.short._ div( p(*.color := "red", *.fontSize := 64.pt)("Big Red Text"), img(*.href := "www.imgur.com/picture.jpg") ) }, { // bundle is scalatags.Text or scalatags.JsDom import bundle.{attrs => attr, styles => css, _} import bundle.tags._ import bundle.implicits._ div( p(css.color := "red", css.fontSize := 64.pt)("Big Red Text"), img(attr.href := "www.imgur.com/picture.jpg") ) }, """ <div> <p style="color: red;">Red Text</p> <img href="www.imgur.com/picture.jpg" /> </div> """) // bundle is scalatags.Text or scalatags.JsDom import bundle.all._ 'splashExample - strCheck( // import scalatags.Text.all._ // OR // import scalatags.JsDom.all._ html( head( script(src := "..."), script( "alert('Hello World')" ) ), body( div( h1(id := "title", "This is a title"), p("This is a big paragraph of text") ) ) ), """ <html> <head> <script src="..."></script> <script>alert('Hello World')</script> </head> <body> <div> <h1 id="title">This is a title</h1> <p>This is a big paragraph of text</p> </div> </body> </html> """ ) 'helloWorld - strCheck( html( head( script("some script") ), body( h1("This is my title"), div( p("This is my first paragraph"), p("This is my second paragraph") ) ) ), """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div> <p>This is my first paragraph</p> <p>This is my second paragraph</p> </div> </body> </html> """ ) 'variables - strCheck( { val title = "title" val numVisitors = 1023 html( head( script("some script") ), body( h1("This is my ", title), div( p("This is my first paragraph"), p("you are the ", numVisitors.toString, "th visitor!") ) ) ) }, """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div> <p>This is my first paragraph</p> <p>you are the 1023th visitor!</p> </div> </body> </html> """ ) 'controlFlow - strCheck( { val numVisitors = 1023 val posts = Seq( ("alice", "i like pie"), ("bob", "pie is evil i hate you"), ("charlie", "i like pie and pie is evil, i hat myself") ) html( head( script("some script") ), body( h1("This is my title"), div("posts"), for ((name, text) <- posts) yield div( h2("Post by ", name), p(text) ), if (numVisitors > 100) p("No more posts!") else p("Please post below...") ) ) }, """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div>posts</div> <div> <h2>Post by alice</h2> <p>i like pie</p> </div> <div> <h2>Post by bob</h2> <p>pie is evil i hate you</p> </div> <div> <h2>Post by charlie</h2> <p>i like pie and pie is evil, i hat myself</p> </div> <p>No more posts!</p> </body> </html> """ ) 'functions - strCheck( { def imgBox(source: String, text: String) = div( img(src := source), div( p(text) ) ) html( head( script("some script") ), body( h1("This is my title"), imgBox("www.mysite.com/imageOne.png", "This is the first image displayed on the site"), div(`class` := "content")( p("blah blah blah i am text"), imgBox("www.mysite.com/imageTwo.png", "This image is very interesting") ) ) ) }, """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div> <img src="www.mysite.com/imageOne.png" /> <div> <p>This is the first image displayed on the site</p> </div> </div> <div class="content"> <p>blah blah blah i am text</p> <div> <img src="www.mysite.com/imageTwo.png" /> <div> <p>This image is very interesting</p> </div> </div> </div> </body> </html> """ ) 'attributes - strCheck( html( head( script("some script") ), body( h1("This is my title"), div( p(onclick := "... do some js")( "This is my first paragraph" ), a(href := "www.google.com")( p("Goooogle") ), p(hidden)( "I am hidden" ) ) ) ), html( head( script("some script") ), body( h1("This is my title"), div( p(attr("onclick") := "... do some js")( "This is my first paragraph" ), a(attr("href") := "www.google.com")( p("Goooogle") ), p(attr("hidden").empty)( "I am hidden" ) ) ) ), """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div> <p onclick="... do some js"> This is my first paragraph</p> <a href="www.google.com"> <p>Goooogle</p> </a> <p hidden="hidden"> I am hidden</p> </div> </body> </html> """ ) 'classesAndCssCustom - strCheck( html( head( script("some script") ), body( h1(backgroundColor := "blue", color := "red")("This is my title"), div(backgroundColor := "blue", color := "red")( p(cls := "contentpara first")( "This is my first paragraph" ), a(opacity := 0.9)( p(cls := "contentpara")("Goooogle") ) ) ) ), html( head( script("some script") ), body( h1(style := "background-color: blue; color: red;")( "This is my title"), div(style := "background-color: blue; color: red;")( p(`class` := "contentpara first")( "This is my first paragraph" ), a(style := "opacity: 0.9;")( p(cls := "contentpara")("Goooogle") ) ) ) ), """ <html> <head> <script>some script</script> </head> <body> <h1 style="background-color: blue; color: red;">This is my title</h1> <div style="background-color: blue; color: red;"> <p class="contentpara first">This is my first paragraph</p> <a style="opacity: 0.9;"> <p class="contentpara">Goooogle</p> </a> </div> </body> </html> """ ) 'nonStringAttributesAndStyles - strCheck( div( p(float.left)( "This is my first paragraph" ), a(tabindex := 10)( p("Goooogle") ), input(disabled := true) ), """ <div> <p style="float: left;">This is my first paragraph</p> <a tabindex="10"> <p>Goooogle</p> </a> <input disabled="true" /> </div> """ ) 'forceStringifyingAttributesAndStyles - strCheck( div( p(float := "left")( "This is my first paragraph" ), a(tabindex := "10")( p("Goooogle") ), input(disabled := "true") ), """ <div> <p style="float: left;">This is my first paragraph</p> <a tabindex="10"> <p>Goooogle</p> </a> <input disabled="true" /> </div> """ ) 'booleanAttributes - strCheck( div(input(readonly)), """ <div><input readonly="readonly" /></div> """ ) 'booleanAttributes2 - strCheck( div(input(readonly := 1)), """ <div><input readonly="1" /></div> """ ) 'layouts - strCheck( { def page(scripts: Seq[Modifier], content: Seq[Modifier]) = html( head(scripts), body( h1("This is my title"), div(cls := "content")(content) ) ) page( Seq( script("some script") ), Seq( p("This is the first ", b("image"), " displayed on the ", a("site")), img(src := "www.myImage.com/image.jpg"), p("blah blah blah i am text") ) ) }, """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <div class="content"> <p>This is the first <b>image</b> displayed on the <a>site</a></p> <img src="www.myImage.com/image.jpg" /> <p>blah blah blah i am text</p> </div> </body> </html> """ ) 'inheritence - strCheck( { class Parent { def render = html( headFrag, bodyFrag ) def headFrag = head( script("some script") ) def bodyFrag = body( h1("This is my title"), div( p("This is my first paragraph"), p("This is my second paragraph") ) ) } object Child extends Parent { override def headFrag = head( script("some other script") ) } Child.render }, """ <html> <head> <script>some other script</script> </head> <body> <h1>This is my title</h1> <div> <p>This is my first paragraph</p> <p>This is my second paragraph</p> </div> </body> </html> """ ) // TODO: Test errors in new jsdom // 'properEscaping - strCheck({ // val evilInput1 = "\"><script>alert('hello!')</script>" // val evilInput2 = "<script>alert('hello!')</script>" // // html( // head( // script("some script") // ), // body( // h1( // title := evilInput1, // "This is my title" // ), // evilInput2 // ) // ) // }, """ // <html> // <head> // <script>some script</script> // </head> // <body> // <h1 title="&quot;&gt;&lt;script&gt;alert('hello!')&lt;/script&gt;"> // This is my title // </h1> // &lt;script&gt;alert('hello!')&lt;/script&gt; // </body> // </html> // """) // TODO: Decide what to do regarding 'raw' // 'unsanitizedInput - strCheck({ // val evilInput = "<script>alert('hello!')</script>" // // html( // head( // script("some script") // ), // body( // h1("This is my title"), // raw(evilInput) // ) // ) // }, """ // <html> // <head> // <script>some script</script> // </head> // <body> // <h1>This is my title</h1> // <script>alert('hello!')</script> // </body> // </html> // """) 'additionalImports - strCheck({ // bundle is scalatags.Text or scalatags.JsDom import bundle._ import styles2.pageBreakBefore import tags2.address import svgTags.svg import svgAttrs.stroke div( p(pageBreakBefore.always, "a long paragraph which should not be broken"), address("500 Memorial Drive, Cambridge MA"), svg(stroke := "#0000ff") ) }, """ <div> <p style="page-break-before: always;"> a long paragraph which should not be broken </p> <address>500 Memorial Drive, Cambridge MA</address> <svg stroke="#0000ff"></svg> </div> """) 'typesafeCSS - strCheck( div(zIndex := 10), """<div style="z-index: 10;"></div>""" ) 'customAttributesAndStyles - strCheck({ div( attr("data-app-key") := "YOUR_APP_KEY", css("background-color") := "red" ) }, { val dataAppKey = attr("data-app-key") val customBackgroundColorStyle = css("background-color") div( dataAppKey := "YOUR_APP_KEY", customBackgroundColorStyle := "red" ) }, """ <div data-app-key="YOUR_APP_KEY" style="background-color: red;"></div> """) 'customTagNames - strCheck({ html( head( script("some script") ), body( h1("This is my title"), p("Hello") ) ) }, tag("html")( tag("head")( tag("script")("some script") ), tag("body")( tag("h1")("This is my title"), tag("p")("Hello") ) ), """ <html> <head> <script>some script</script> </head> <body> <h1>This is my title</h1> <p>Hello</p> </body> </html> """) 'aria - strCheck( div( div(id := "ch1Panel", role := "tabpanel", aria.labelledby := "ch1Tab")( "Chapter 1 content goes here" ), div(id := "ch2Panel", role := "tabpanel", aria.labelledby := "ch2Tab")( "Chapter 2 content goes here" ), div(id := "quizPanel", role := "tabpanel", aria.labelledby := "quizTab")( "Quiz content goes here" ) ), """ <div> <div id="ch1Panel" role="tabpanel" aria-labelledby="ch1Tab"> Chapter 1 content goes here </div> <div id="ch2Panel" role="tabpanel" aria-labelledby="ch2Tab"> Chapter 2 content goes here </div> <div id="quizPanel" role="tabpanel" aria-labelledby="quizTab"> Quiz content goes here </div> </div> """ ) 'data - strCheck( div( id := "electriccars", data.columns := "3", data.index.number := "12314", data.parent := "cars", "..." ), """ <div id="electriccars" data-columns="3" data-index-number="12314" data-parent="cars"> ... </div> """ ) } }
tzbob/scalatags-hokko
modules/core/src/test/scala/scalatags/generic/ExampleTests.scala
Scala
mit
17,540
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.expressions.aggregate import java.nio.ByteBuffer import com.google.common.primitives.{Doubles, Ints, Longs} import org.apache.spark.sql.AnalysisException import org.apache.spark.sql.catalyst.{InternalRow} import org.apache.spark.sql.catalyst.analysis.TypeCheckResult import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.{TypeCheckFailure, TypeCheckSuccess} import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.aggregate.ApproximatePercentile.{PercentileDigest} import org.apache.spark.sql.catalyst.util.{ArrayData, GenericArrayData} import org.apache.spark.sql.catalyst.util.QuantileSummaries import org.apache.spark.sql.catalyst.util.QuantileSummaries.{defaultCompressThreshold, Stats} import org.apache.spark.sql.types._ /** * The ApproximatePercentile function returns the approximate percentile(s) of a column at the given * percentage(s). A percentile is a watermark value below which a given percentage of the column * values fall. For example, the percentile of column `col` at percentage 50% is the median of * column `col`. * * This function supports partial aggregation. * * @param child child expression that can produce column value with `child.eval(inputRow)` * @param percentageExpression Expression that represents a single percentage value or * an array of percentage values. Each percentage value must be between * 0.0 and 1.0. * @param accuracyExpression Integer literal expression of approximation accuracy. Higher value * yields better accuracy, the default value is * DEFAULT_PERCENTILE_ACCURACY. */ @ExpressionDescription( usage = """ _FUNC_(col, percentage [, accuracy]) - Returns the approximate percentile value of numeric column `col` at the given percentage. The value of percentage must be between 0.0 and 1.0. The `accuracy` parameter (default: 10000) is a positive numeric literal which controls approximation accuracy at the cost of memory. Higher value of `accuracy` yields better accuracy, `1.0/accuracy` is the relative error of the approximation. When `percentage` is an array, each value of the percentage array must be between 0.0 and 1.0. In this case, returns the approximate percentile array of column `col` at the given percentage array. """, extended = """ Examples: > SELECT _FUNC_(10.0, array(0.5, 0.4, 0.1), 100); [10.0,10.0,10.0] > SELECT _FUNC_(10.0, 0.5, 100); 10.0 """) case class ApproximatePercentile( child: Expression, percentageExpression: Expression, accuracyExpression: Expression, override val mutableAggBufferOffset: Int, override val inputAggBufferOffset: Int) extends TypedImperativeAggregate[PercentileDigest] { def this(child: Expression, percentageExpression: Expression, accuracyExpression: Expression) = { this(child, percentageExpression, accuracyExpression, 0, 0) } def this(child: Expression, percentageExpression: Expression) = { this(child, percentageExpression, Literal(ApproximatePercentile.DEFAULT_PERCENTILE_ACCURACY)) } // Mark as lazy so that accuracyExpression is not evaluated during tree transformation. private lazy val accuracy: Int = accuracyExpression.eval().asInstanceOf[Int] override def inputTypes: Seq[AbstractDataType] = { Seq(DoubleType, TypeCollection(DoubleType, ArrayType), IntegerType) } // Mark as lazy so that percentageExpression is not evaluated during tree transformation. private lazy val (returnPercentileArray: Boolean, percentages: Array[Double]) = { (percentageExpression.dataType, percentageExpression.eval()) match { // Rule ImplicitTypeCasts can cast other numeric types to double case (_, num: Double) => (false, Array(num)) case (ArrayType(baseType: NumericType, _), arrayData: ArrayData) => val numericArray = arrayData.toObjectArray(baseType) (true, numericArray.map { x => baseType.numeric.toDouble(x.asInstanceOf[baseType.InternalType]) }) case other => throw new AnalysisException(s"Invalid data type ${other._1} for parameter percentage") } } override def checkInputDataTypes(): TypeCheckResult = { val defaultCheck = super.checkInputDataTypes() if (defaultCheck.isFailure) { defaultCheck } else if (!percentageExpression.foldable || !accuracyExpression.foldable) { TypeCheckFailure(s"The accuracy or percentage provided must be a constant literal") } else if (accuracy <= 0) { TypeCheckFailure( s"The accuracy provided must be a positive integer literal (current value = $accuracy)") } else if (percentages.exists(percentage => percentage < 0.0D || percentage > 1.0D)) { TypeCheckFailure( s"All percentage values must be between 0.0 and 1.0 " + s"(current = ${percentages.mkString(", ")})") } else { TypeCheckSuccess } } override def createAggregationBuffer(): PercentileDigest = { val relativeError = 1.0D / accuracy new PercentileDigest(relativeError) } override def update(buffer: PercentileDigest, inputRow: InternalRow): Unit = { val value = child.eval(inputRow) // Ignore empty rows, for example: percentile_approx(null) if (value != null) { buffer.add(value.asInstanceOf[Double]) } } override def merge(buffer: PercentileDigest, other: PercentileDigest): Unit = { buffer.merge(other) } override def eval(buffer: PercentileDigest): Any = { val result = buffer.getPercentiles(percentages) if (result.length == 0) { null } else if (returnPercentileArray) { new GenericArrayData(result) } else { result(0) } } override def withNewMutableAggBufferOffset(newOffset: Int): ApproximatePercentile = copy(mutableAggBufferOffset = newOffset) override def withNewInputAggBufferOffset(newOffset: Int): ApproximatePercentile = copy(inputAggBufferOffset = newOffset) override def children: Seq[Expression] = Seq(child, percentageExpression, accuracyExpression) // Returns null for empty inputs override def nullable: Boolean = true override def dataType: DataType = { if (returnPercentileArray) ArrayType(DoubleType) else DoubleType } override def prettyName: String = "percentile_approx" override def serialize(obj: PercentileDigest): Array[Byte] = { ApproximatePercentile.serializer.serialize(obj) } override def deserialize(bytes: Array[Byte]): PercentileDigest = { ApproximatePercentile.serializer.deserialize(bytes) } } object ApproximatePercentile { // Default accuracy of Percentile approximation. Larger value means better accuracy. // The default relative error can be deduced by defaultError = 1.0 / DEFAULT_PERCENTILE_ACCURACY val DEFAULT_PERCENTILE_ACCURACY: Int = 10000 /** * PercentileDigest is a probabilistic data structure used for approximating percentiles * with limited memory. PercentileDigest is backed by [[QuantileSummaries]]. * * @param summaries underlying probabilistic data structure [[QuantileSummaries]]. * @param isCompressed An internal flag from class [[QuantileSummaries]] to indicate whether the * underlying quantileSummaries is compressed. */ class PercentileDigest( private var summaries: QuantileSummaries, private var isCompressed: Boolean) { // Trigger compression if the QuantileSummaries's buffer length exceeds // compressThresHoldBufferLength. The buffer length can be get by // quantileSummaries.sampled.length private[this] final val compressThresHoldBufferLength: Int = { // Max buffer length after compression. val maxBufferLengthAfterCompression: Int = (1 / summaries.relativeError).toInt * 2 // A safe upper bound for buffer length before compression maxBufferLengthAfterCompression * 2 } def this(relativeError: Double) = { this(new QuantileSummaries(defaultCompressThreshold, relativeError), isCompressed = true) } /** Returns compressed object of [[QuantileSummaries]] */ def quantileSummaries: QuantileSummaries = { if (!isCompressed) compress() summaries } /** Insert an observation value into the PercentileDigest data structure. */ def add(value: Double): Unit = { summaries = summaries.insert(value) // The result of QuantileSummaries.insert is un-compressed isCompressed = false // Currently, QuantileSummaries ignores the construction parameter compressThresHold, // which may cause QuantileSummaries to occupy unbounded memory. We have to hack around here // to make sure QuantileSummaries doesn't occupy infinite memory. // TODO: Figure out why QuantileSummaries ignores construction parameter compressThresHold if (summaries.sampled.length >= compressThresHoldBufferLength) compress() } /** In-place merges in another PercentileDigest. */ def merge(other: PercentileDigest): Unit = { if (!isCompressed) compress() summaries = summaries.merge(other.quantileSummaries) } /** * Returns the approximate percentiles of all observation values at the given percentages. * A percentile is a watermark value below which a given percentage of observation values fall. * For example, the following code returns the 25th, median, and 75th percentiles of * all observation values: * * {{{ * val Array(p25, median, p75) = percentileDigest.getPercentiles(Array(0.25, 0.5, 0.75)) * }}} */ def getPercentiles(percentages: Array[Double]): Array[Double] = { if (!isCompressed) compress() if (summaries.count == 0 || percentages.length == 0) { Array.empty[Double] } else { val result = new Array[Double](percentages.length) var i = 0 while (i < percentages.length) { result(i) = summaries.query(percentages(i)) i += 1 } result } } private final def compress(): Unit = { summaries = summaries.compress() isCompressed = true } } /** * Serializer for class [[PercentileDigest]] * * This class is thread safe. */ class PercentileDigestSerializer { private final def length(summaries: QuantileSummaries): Int = { // summaries.compressThreshold, summary.relativeError, summary.count Ints.BYTES + Doubles.BYTES + Longs.BYTES + // length of summary.sampled Ints.BYTES + // summary.sampled, Array[Stat(value: Double, g: Int, delta: Int)] summaries.sampled.length * (Doubles.BYTES + Ints.BYTES + Ints.BYTES) } final def serialize(obj: PercentileDigest): Array[Byte] = { val summary = obj.quantileSummaries val buffer = ByteBuffer.wrap(new Array(length(summary))) buffer.putInt(summary.compressThreshold) buffer.putDouble(summary.relativeError) buffer.putLong(summary.count) buffer.putInt(summary.sampled.length) var i = 0 while (i < summary.sampled.length) { val stat = summary.sampled(i) buffer.putDouble(stat.value) buffer.putInt(stat.g) buffer.putInt(stat.delta) i += 1 } buffer.array() } final def deserialize(bytes: Array[Byte]): PercentileDigest = { val buffer = ByteBuffer.wrap(bytes) val compressThreshold = buffer.getInt() val relativeError = buffer.getDouble() val count = buffer.getLong() val sampledLength = buffer.getInt() val sampled = new Array[Stats](sampledLength) var i = 0 while (i < sampledLength) { val value = buffer.getDouble() val g = buffer.getInt() val delta = buffer.getInt() sampled(i) = Stats(value, g, delta) i += 1 } val summary = new QuantileSummaries(compressThreshold, relativeError, sampled, count) new PercentileDigest(summary, isCompressed = true) } } val serializer: PercentileDigestSerializer = new PercentileDigestSerializer }
u2009cf/spark-radar
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/ApproximatePercentile.scala
Scala
apache-2.0
12,987
package org.scaladebugger.api.profiles import _root_.java.util.concurrent.ConcurrentHashMap import _root_.java.util.concurrent.atomic.AtomicInteger import com.sun.jdi.event.Event import org.scaladebugger.api.lowlevel.events.EventType.EventType import org.scaladebugger.api.lowlevel.events.data.JDIEventDataResult import org.scaladebugger.api.lowlevel.events.filters.UniqueIdPropertyFilter import org.scaladebugger.api.lowlevel.events.{EventManager, JDIEventArgument} import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument import org.scaladebugger.api.lowlevel.requests.properties.UniqueIdProperty import org.scaladebugger.api.lowlevel.{JDIArgument, RequestInfo} import org.scaladebugger.api.pipelines.Pipeline import org.scaladebugger.api.pipelines.Pipeline.IdentityPipeline import org.scaladebugger.api.profiles.traits.info.events.EventInfo import org.scaladebugger.api.utils.{Memoization, MultiMap} import org.scaladebugger.api.virtualmachines.ScalaVirtualMachine import scala.collection.JavaConverters._ import scala.util.Try /** * Represents the base request that abstracts functionality common * among all requests. * * @param scalaVirtualMachine The destination for the requests * @param eventManager The low-level event manager to listen to events * @param etInstance The type of event to * @param _newRequestId Generates a new request id * @param _newRequest Creates a new request using the provided request id, * request arguments, and collection of JDI arguments * @param _hasRequest Determines whether a request exists with the provided * request arguments * @param _removeRequestById Removes a request using its id * @param _newEventInfo Creates a new event info pipeline using the provided * Scala virtual machine, JDI event, and collection of * JDI arguments * @param _retrieveRequestInfo Retrieves the information for a request using its * request id, returning Some(info) if found * @param _includeUniqueId If true, includes a unique id on each new request * and filters the generated pipelines using the * unique id property filter (should be set to false * for events without requests such as VM Start) * @tparam E The JDI event * @tparam EI The event info type to transform the JDI event into * @tparam RequestArgs The arguments used to create a request * @tparam CounterKey The key to use when looking up a pipeline counter to * increment or decrement */ class RequestHelper[ E <: Event, EI <: EventInfo, RequestArgs, CounterKey ]( protected val scalaVirtualMachine: ScalaVirtualMachine, protected val eventManager: EventManager, private[profiles] val etInstance: EventType, private[profiles] val _newRequestId: () => String, private[profiles] val _newRequest: (String, RequestArgs, Seq[JDIRequestArgument]) => Try[String], private[profiles] val _hasRequest: (RequestArgs) => Boolean, private[profiles] val _removeRequestById: String => Unit, private[profiles] val _newEventInfo: (ScalaVirtualMachine, E, Seq[JDIArgument]) => EI, private[profiles] val _retrieveRequestInfo: String => Option[RequestInfo], private[profiles] val _includeUniqueId: Boolean = true ) { // Do not allow any argument to be null (stop at front door) require( scalaVirtualMachine != null && eventManager != null && etInstance != null && _newRequestId != null && _newRequest != null && _hasRequest != null && _removeRequestById != null && _newEventInfo != null && _removeRequestById != null ) /** Represents the combination of event and data returned. */ type EventAndData = (EI, Seq[JDIEventDataResult]) /** Represents the manager of the Scala virtual machine. */ private lazy val scalaVirtualMachineManager = scalaVirtualMachine.manager /** * Contains a mapping of request ids to associated event handler ids. */ private val pipelineRequestEventIds = new MultiMap[String, String] /** * Contains mapping from input to a counter indicating how many pipelines * are currently active for the input. */ private val pipelineCounter = new ConcurrentHashMap[CounterKey, AtomicInteger]().asScala /** * Creates a new request using the given arguments. The * request is memoized, meaning that the same request will be returned for * the same arguments. The memoized result will be thrown out if the * underlying request storage indicates that the request has been removed. * * @param requestArgs The custom request arguments * @param jdiRequestArgs The JDI request arguments * @return Success containing the event id, otherwise a failure */ def newRequest( requestArgs: RequestArgs, jdiRequestArgs: Seq[JDIRequestArgument] ) = newRequestImpl(requestArgs, jdiRequestArgs) /** Represents the internal implementation of newRequest. */ private lazy val newRequestImpl = { type Input = (RequestArgs, Seq[JDIRequestArgument]) type Key = (RequestArgs, Seq[JDIRequestArgument]) type Output = Try[String] val m = new Memoization[Input, Key, Output]( memoFunc = (input: Input) => { val requestId = _newRequestId() val args = if (_includeUniqueId) UniqueIdProperty(id = requestId) +: input._2 else input._2 _newRequest(requestId, input._1, args) }, cacheInvalidFunc = (key: Key) => !_hasRequest(key._1) ) (requestArgs: RequestArgs, jdiRequestArgs: Seq[JDIRequestArgument]) => Try(m((requestArgs, jdiRequestArgs))).flatten } /** * Creates a new pipeline of events and data using the given * arguments. The pipeline is NOT memoized; therefore, each call creates a * new pipeline with a new underlying event handler feeding the pipeline. * This means that the pipeline needs to be properly closed to remove the * event handler. * * @param requestId The id of the request whose events to stream through the * new pipeline * @param counterKey The key used to increment and decrement the underlying * pipeline counter * @return Success containing new event and data pipeline, otherwise a failure */ def newEventPipeline( requestId: String, eventArgs: Seq[JDIEventArgument], counterKey: CounterKey ): Try[IdentityPipeline[EventAndData]] = Try { // Lookup final set of request arguments used when creating the request val rArgs = _retrieveRequestInfo(requestId) .map(_.extraArguments).getOrElse(Nil) val eArgsWithFilter = if (_includeUniqueId) UniqueIdPropertyFilter(id = requestId) +: eventArgs else eventArgs val newPipeline = newEventStream(rArgs, eArgsWithFilter) // Create a companion pipeline who, when closed, checks to see if there // are no more pipelines for the given request and, if so, removes the // request as well val closePipeline = Pipeline.newPipeline( classOf[EventAndData], newPipelineCloseFunc(requestId, counterKey) ) val combinedPipeline = newPipeline.unionOutput(closePipeline) // Increment the counter for open pipelines pipelineCounter .getOrElseUpdate(counterKey, new AtomicInteger(0)) .incrementAndGet() // Store the new event handler id as associated with the current request pipelineRequestEventIds.put( requestId, combinedPipeline.currentMetadata( EventManager.EventHandlerIdMetadataField ).asInstanceOf[String] ) combinedPipeline } /** * Creates an event stream pipeline using the provided request and event * arguments as input to creating the new event stream. * * @param requestArgs The request arguments to use when creating the stream * @param eventArgs The event arguments to use when creating the stream * @return A new pipeline of events and associated data */ private def newEventStream( requestArgs: Seq[JDIRequestArgument], eventArgs: Seq[JDIEventArgument] ): IdentityPipeline[EventAndData] = { val allArgs = (requestArgs ++ eventArgs).distinct eventManager .addEventDataStream(etInstance, eventArgs: _*) .map(t => (t._1.asInstanceOf[E], t._2)) .map(t => { val vm = Try(t._1.virtualMachine()) val svm = vm.flatMap(vm => Try(scalaVirtualMachineManager(vm))) svm.map(s => (_newEventInfo(s, t._1, allArgs), t._2)).get }).noop() } /** * Creates a new function used for closing generated pipelines. * * @param requestId The id of the request * @param counterKey The key used to decrement the underlying pipeline counter * @return The new function for closing the pipeline */ private def newPipelineCloseFunc( requestId: String, counterKey: CounterKey ): (Option[Any]) => Unit = (data: Option[Any]) => { val pCounter = pipelineCounter(counterKey) val totalPipelinesRemaining = pCounter.decrementAndGet() import org.scaladebugger.api.profiles.Constants.CloseRemoveAll if (totalPipelinesRemaining == 0 || data.exists(_ == CloseRemoveAll)) { _removeRequestById(requestId) pipelineRequestEventIds.remove(requestId).foreach( _.foreach(eventManager.removeEventHandler) ) pCounter.set(0) } } }
ensime/scala-debugger
scala-debugger-api/src/main/scala/org/scaladebugger/api/profiles/RequestHelper.scala
Scala
apache-2.0
9,374
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.selenium import org.openqa.selenium.WebDriver import org.openqa.selenium.firefox.FirefoxDriver import org.openqa.selenium.firefox.FirefoxProfile import org.openqa.selenium.safari.SafariDriver import org.openqa.selenium.chrome.ChromeDriver import org.openqa.selenium.ie.InternetExplorerDriver import org.openqa.selenium.htmlunit.HtmlUnitDriver import org.openqa.selenium.By import org.openqa.selenium.WebElement import java.util.concurrent.TimeUnit import org.openqa.selenium.support.ui.WebDriverWait import org.openqa.selenium.support.ui.Clock import org.openqa.selenium.support.ui.Sleeper import org.openqa.selenium.support.ui.ExpectedCondition import scala.collection.mutable.Buffer import scala.collection.JavaConverters._ import org.openqa.selenium.Cookie import java.util.Date import org.scalatest.time.Span import org.scalatest.time.Milliseconds import org.openqa.selenium.TakesScreenshot import org.openqa.selenium.OutputType import java.io.File import java.io.FileOutputStream import java.io.FileInputStream import org.openqa.selenium.Alert import org.openqa.selenium.support.ui.Select import org.scalatest.exceptions.TestFailedException import org.scalatest.exceptions.StackDepthException import org.openqa.selenium.JavascriptExecutor import org.scalatest.ScreenshotCapturer import org.scalatest.time.Nanosecond import org.scalatest.Resources /** * Trait that provides a domain specific language (DSL) for writing browser-based tests using <a href="http://seleniumhq.org">Selenium</a>. * * To use ScalaTest's Selenium DSL, mix trait <code>WebBrowser</code> into your test class. This trait provides the DSL in its * entirety except for one missing piece: an implicit <code>org.openqa.selenium.WebDriver</code>. One way to provide the missing * implicit driver is to declare one as a member of your test class, like this: * * <pre class="stHighlight"> * import org.scalatest._ * import selenium._ * import org.openqa.selenium._ * import htmlunit._ * * class BlogSpec extends FlatSpec with Matchers with WebBrowser { * * implicit val webDriver: WebDriver = new HtmlUnitDriver * * val host = "http://localhost:9000/" * * "The blog app home page" should "have the correct title" in { * go to (host + "index.html") * pageTitle should be ("Awesome Blog") * } * } * </pre> * * <p> * For convenience, however, ScalaTest provides a <code>WebBrowser</code> subtrait containing an implicit <code>WebDriver</code> for each * driver provided by Selenium. * Thus a simpler way to use the <code>HtmlUnit</code> driver, for example, is to extend * ScalaTest's <a href="HtmlUnit.html"><code>HtmlUnit</code></a> trait, like this: * </p> * * <pre class="stHighlight"> * import org.scalatest._ * import selenium._ * * class BlogSpec extends FlatSpec with Matchers with HtmlUnit { * * val host = "http://localhost:9000/" * * "The blog app home page" should "have the correct title" in { * go to (host + "index.html") * pageTitle should be ("Awesome Blog") * } * } * </pre> * * <p> * The web driver traits provided by ScalaTest are: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Driver</strong></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong><code>WebBrowser</code> subtrait</strong></th></tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * Google Chrome * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <a href="Chrome.html"><code>Chrome</code></a> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * Mozilla Firefox * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <a href="Firefox.html"><code>Firefox</code></a> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * HtmlUnit * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <a href="HtmlUnit.html"><code>HtmlUnit</code></a> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * Microsoft Internet Explorer * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <a href="InternetExplorer.html"><code>InternetExplorer</code></a> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * Apple Safari * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <a href="Safari.html"><code>Safari</code></a> * </td> * </tr> * </table> * * <h2>Navigation</h2> * * <p> * You can ask the browser to retrieve a page (go to a URL) like this: * </p> * * <pre class="stHighlight"> * go to "http://www.artima.com" * </pre> * * <p> * Note: If you are using the <em>page object pattern</em>, you can also go to a page using the <code>Page</code> instance, as * illustrated in the section on <a href="#pageObjects">page objects</a> below. * </p> * * <p> * Once you have retrieved a page, you can fill in and submit forms, query for the values of page elements, and make assertions. * In the following example, selenium will go to <code>http://www.google.com</code>, fill in the text box with * <code>Cheese!</code>, press the submit button, and wait for result returned from an AJAX call: * </p> * * <pre class="stHighlight"> * go to "http://www.google.com" * click on "q" * enter("Cheese!") * submit() * // Google's search is rendered dynamically with JavaScript. * eventually { pageTitle should be ("Cheese! - Google Search") } * </pre> * * <p> * In the above example, the <code>"q"</code> used in &ldquo;<code>click on "q"</code>&rdquo; * can be either the id or name of an element. ScalaTest's Selenium DSL will try to lookup by id first. If it cannot find * any element with an id equal to <code>&quot;q&quot;</code>, it will then try lookup by name <code>&quot;q&quot;</code>. * </p> * * <p> * Alternatively, you can be more specific: * </p> * * <pre class="stHighlight"> * click on id("q") // to lookup by id "q" * click on name("q") // to lookup by name "q" * </pre> * * <p> * In addition to <code>id</code> and <code>name</code>, you can use the following approaches to lookup elements, just as you can do with * Selenium's <code>org.openqa.selenium.By</code> class: * </p> * * <ul> * <li><code>xpath</code></li> * <li><code>className</code></li> * <li><code>cssSelector</code></li> * <li><code>linkText</code></li> * <li><code>partialLinkText</code></li> * <li><code>tagName</code></li> * </ul> * * <p> * For example, you can select by link text with: * </p> * * <pre class="stHighlight"> * click on linkText("click here!") * </pre> * * <p> * If an element is not found via any form of lookup, evaluation will complete abruptly with a <code>TestFailedException</code>. * <p> * * <h2>Getting and setting input element values</h2> * * <p> * ScalaTest's Selenium DSL provides a clear, simple syntax for accessing and updating the values of input elements such as * text fields, radio buttons, checkboxes, selection lists, and the input types introduced in HTML5. If a requested element is not found, or if it is found but is * not of the requested type, an exception will immediately result causing the test to fail. * <p> * * <p> * The most common way to access field value is through the <code>value</code> property, which is supported by the following * input types: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr> * <th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"> * <strong>Tag Name</strong> * </th> * <th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"> * <strong>Input Type</strong> * </th> * <th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"> * <strong>Lookup Method</strong> * </th> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>text</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>textField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>textarea</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>-</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>textArea</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>password</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>pwdField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>email</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>emailField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>color</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>colorField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>date</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>dateField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>datetime</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>dateTimeField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>datetime-local</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>dateTimeLocalField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>month</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>monthField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>number</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>numberField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>range</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>rangeField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>search</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>searchField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>tel</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>telField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>time</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>timeField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>url</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>urlField</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>input</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>week</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * <code>weekField</code> * </td> * </tr> * </table> * * <p> * You can change a input field's value by assigning it via the <code>=</code> operator, like this: * </p> * * <pre class="stHighlight"> * textField("q").value = "Cheese!" * </pre> * * <p> * And you can access a input field's value by simply invoking <code>value</code> on it: * </p> * * <pre class="stHighlight"> * textField("q").value should be ("Cheese!") * </pre> * * <p> * If the text field is empty, <code>value</code> will return an empty string (<code>""</code>). * </p> * * <p> * You can use the same syntax with other type of input fields by replacing <code>textField</code> with <code>Lookup Method</code> listed in table above, * for example to use text area: * </p> * * <pre class="stHighlight"> * textArea("body").value = "I saw something cool today!" * textArea("body").value should be ("I saw something cool today!") * </pre> * * <p> * or with a password field: * </p> * * <pre class="stHighlight"> * pwdField("secret").value = "Don't tell anybody!" * pwdField("secret").value should be ("Don't tell anybody!") * </pre> * * <h3>Alternate Way for Data Entry</h3> * * <p> * An alternate way to enter data into a input fields is to use <code>enter</code> or <code>pressKeys</code>. * Although both of <code>enter</code> and <code>pressKeys</code> send characters to the active element, <code>pressKeys</code> can be used on any kind of * element, whereas <code>enter</code> can only be used on text entry fields, which include: * </p> * * <ul> * <li><code>textField</code></li> * <li><code>textArea</code></li> * <li><code>pwdField</code></li> * <li><code>emailField</code></li> * <li><code>searchField</code></li> * <li><code>telField</code></li> * <li><code>urlField</code></li> * </ul> * * <p> * Another difference is that <code>enter</code> will clear the text field or area before sending the characters, * effectively replacing any currently existing text with the new text passed to <code>enter</code>. By contrast, * <code>pressKeys</code> does not do any clearing&#8212;it just appends more characters to any existing text. * You can backup with <code>pressKeys</code>, however, by sending explicit backspace characters, <code>"&#92;u0008"</code>. * </p> * * <p> * To use these commands, you must first click on the input field you are interested in * to give it the focus. Here's an example: * </p> * * <pre class="stHighlight"> * click on "q" * enter("Cheese!") * </pre> * * <p> * Here's a (contrived) example of using <code>pressKeys</code> with backspace to fix a typo: * </p> * * <pre class="stHighlight"> * click on "q" // q is the name or id of a text field or text area * enter("Cheesey!") // Oops, meant to say Cheese! * pressKeys("&#92;u0008&#92;u0008") // Send two backspaces; now the value is Cheese * pressKeys("!") // Send the missing exclamation point; now the value is Cheese! * </pre> * * <h3>Radio buttons</h3> * * <p> * Radio buttons work together in groups. For example, you could have a group of radio buttons, like this: * </p> * * <pre> * &lt;input type="radio" id="opt1" name="group1" value="Option 1"&gt; Option 1&lt;/input&gt; * &lt;input type="radio" id="opt2" name="group1" value="Option 2"&gt; Option 2&lt;/input&gt; * &lt;input type="radio" id="opt3" name="group1" value="Option 3"&gt; Option 3&lt;/input&gt; * </pre> * * <p> * You can select an option in either of two ways: * </p> * * <pre class="stHighlight"> * radioButtonGroup("group1").value = "Option 2" * radioButtonGroup("group1").selection = Some("Option 2") * </pre> * * <p> * Likewise, you can read the currently selected value of a group of radio buttons in two ways: * </p> * * <pre class="stHighlight"> * radioButtonGroup("group1").value should be ("Option 2") * radioButtonGroup("group1").selection should be (Some("Option 2")) * </pre> * * <p> * If the radio button has no selection at all, <code>selection</code> will return <code>None</code> whereas <code>value</code> * will throw a <code>TestFailedException</code>. By using <code>value</code>, you are indicating you expect a selection, and if there * isn't a selection that should result in a failed test. * </p> * * <p> * If you would like to work with <code>RadioButton</code> element directly, you can select it by calling <code>radioButton</code>: * </p> * * <pre class="stHighlight"> * click on radioButton("opt1") * </pre> * * <p> * you can check if an option is selected by calling <code>isSelected</code>: * </p> * * <pre class="stHighlight"> * radioButton("opt1").isSelected should be (true) * </pre> * * <p> * to get the value of radio button, you can call <code>value</code>: * </p> * * <pre class="stHighlight"> * radioButton("opt1").value should be ("Option 1") * </pre> * * <h3>Checkboxes</h3> * * <p> * A checkbox in one of two states: selected or cleared. Here's how you select a checkbox: * </p> * * <pre class="stHighlight"> * checkbox("cbx1").select() * </pre> * * <p> * And here's how you'd clear one: * </p> * * <pre class="stHighlight"> * checkbox("cbx1").clear() * </pre> * * <p> * You can access the current state of a checkbox with <code>isSelected</code>: * </p> * * <pre class="stHighlight"> * checkbox("cbx1").isSelected should be (true) * </pre> * * <h3>Single-selection dropdown lists</h3> * * <p> * Given the following single-selection dropdown list: * </p> * * <pre> * &lt;select id="select1"&gt; * &lt;option value="option1"&gt;Option 1&lt;/option&gt; * &lt;option value="option2"&gt;Option 2&lt;/option&gt; * &lt;option value="option3"&gt;Option 3&lt;/option&gt; * &lt;/select&gt; * </pre> * * <p> * You could select <code>Option 2</code> in either of two ways: * </p> * * <pre class="stHighlight"> * singleSel("select1").value = "option2" * singleSel("select1").selection = Some("option2") * </pre> * * <p> * To clear the selection, either invoke <code>clear</code> or set <code>selection</code> to <code>None</code>: * </p> * * <pre class="stHighlight"> * singleSel("select1").clear() * singleSel("select1").selection = None * </pre> * * <p> * You can read the currently selected value of a single-selection list in the same manner as radio buttons: * </p> * * <pre class="stHighlight"> * singleSel("select1").value should be ("option2") * singleSel("select1").selection should be (Some("option2")) * </pre> * * <p> * If the single-selection list has no selection at all, <code>selection</code> will return <code>None</code> whereas <code>value</code> * will throw a <code>TestFailedException</code>. By using <code>value</code>, you are indicating you expect a selection, and if there * isn't a selection that should result in a failed test. * </p> * * <h3>Multiple-selection lists</h3> * * <p> * Given the following multiple-selection list: * </p> * * <pre> * &lt;select name="select2" multiple="multiple"&gt; * &lt;option value="option4"&gt;Option 4&lt;/option&gt; * &lt;option value="option5"&gt;Option 5&lt;/option&gt; * &lt;option value="option6"&gt;Option 6&lt;/option&gt; * &lt;/select&gt; * </pre> * * <p> * You could select <code>Option 5</code> and <code>Option 6</code> like this: * </p> * * <pre class="stHighlight"> * multiSel("select2").values = Seq("option5", "option6") * </pre> * * <p> * The previous command would essentially clear all selections first, then select <code>Option 5</code> and <code>Option 6</code>. * If instead you want to <em>not</em> clear any existing selection, just additionally select <code>Option 5</code> and <code>Option 6</code>, * you can use the <code>+=</code> operator, like this. * </p> * * <pre class="stHighlight"> * multiSel("select2").values += "option5" * multiSel("select2").values += "option6" * </pre> * * <p> * To clear a specific option, pass its name to <code>clear</code>: * </p> * * <pre class="stHighlight"> * multiSel("select2").clear("option5") * </pre> * * <p> * To clear all selections, call <code>clearAll</code>: * </p> * * <pre class="stHighlight"> * multiSel("select2").clearAll() * </pre> * * <p> * You can access the current selections with <code>values</code>, which returns an immutable <code>IndexedSeq[String]</code>: * </p> * * <pre class="stHighlight"> * multiSel("select2").values should have size 2 * multiSel("select2").values(0) should be ("option5") * multiSel("select2").values(1) should be ("option6") * </pre> * * <h3>Clicking and submitting</h3> * * <p> * You can click on any element with &ldquo;<code>click on</code>&rdquo; as shown previously: * </p> * * <pre class="stHighlight"> * click on "aButton" * click on name("aTextField") * </pre> * * <p> * If the requested element is not found, <code>click on</code> will throw an exception, failing the test. * </p> * * <p> * Clicking on a input element will give it the focus. If current focus is in on an input element within a form, you can submit the form by * calling <code>submit</code>: * </p> * * <pre class="stHighlight"> * submit() * </pre> * * <h2>Switching</h2> * * <p> * You can switch to a popup alert bo using the following code: * </p> * * <pre class="stHighlight"> * switch to alertBox * </pre> * * <p> * to switch to a frame, you could: * </p> * * <pre class="stHighlight"> * switch to frame(0) // switch by index * switch to frame("name") // switch by name * </pre> * * <p> * If you have reference to a window handle (can be obtained from calling windowHandle/windowHandles), you can switch to a particular * window by: * </p> * * <pre class="stHighlight"> * switch to window(windowHandle) * </pre> * * <p> * You can also switch to active element and default content: * </p> * * <pre class="stHighlight"> * switch to activeElement * switch to defaultContent * </pre> * * <h2>Navigation history</h2> * * <p> * In real web browser, you can press the 'Back' button to go back to previous page. To emulate that action in your test, you can call <code>goBack</code>: * </p> * * <pre class="stHighlight"> * goBack() * </pre> * * <p> * To emulate the 'Forward' button, you can call: * </p> * * <pre class="stHighlight"> * goForward() * </pre> * * And to refresh or reload the current page, you can call: * * <pre class="stHighlight"> * reloadPage() * </pre> * * <h2>Cookies!</h2> * * <p>To create a new cookie, you'll say:</p> * * <pre class="stHighlight"> * add cookie ("cookie_name", "cookie_value") * </pre> * * <p> * to read a cookie value, you do: * </p> * * <pre class="stHighlight"> * cookie("cookie_name").value should be ("cookie_value") // If value is undefined, throws TFE right then and there. Never returns null. * </pre> * * <p> * In addition to the common use of name-value cookie, you can pass these extra fields when creating the cookie, available ways are: * </p> * * <pre class="stHighlight"> * cookie(name: String, value: String) * cookie(name: String, value: String, path: String) * cookie(name: String, value: String, path: String, expiry: Date) * cookie(name: String, value: String, path: String, expiry: Date, domain: String) * cookie(name: String, value: String, path: String, expiry: Date, domain: String, secure: Boolean) * </pre> * * and to read those extra fields: * * <pre class="stHighlight"> * cookie("cookie_name").value // Read cookie's value * cookie("cookie_name").path // Read cookie's path * cookie("cookie_name").expiry // Read cookie's expiry * cookie("cookie_name").domain // Read cookie's domain * cookie("cookie_name").isSecure // Read cookie's isSecure flag * </pre> * * <p> * In order to delete a cookie, you could use the following code: * </p> * * <pre class="stHighlight"> * delete cookie "cookie_name" * </pre> * * <p> * or to delete all cookies in the same domain:- * </p> * * <pre class="stHighlight"> * delete all cookies * </pre> * * To get the underlying Selenium cookie, you can use <code>underlying</code>: * * <pre class="stHighlight"> * cookie("cookie_name").underlying.validate() // call the validate() method on underlying Selenium cookie * </pre> * * <h2>Other useful element properties</h2> * * <p> * All element types (<code>textField</code>, <code>textArea</code>, <code>radioButton</code>, <code>checkbox</code>, <code>singleSel</code>, <code>multiSel</code>) * support the following useful properties: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Method</strong></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Description</strong></th></tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>location</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * The XY location of the top-left corner of this <code>Element</code>. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>size</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * The width/height size of this <code>Element</code>. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>isDisplayed</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * Indicates whether this <code>Element</code> is displayed. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>isEnabled</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * Indicates whether this <code>Element</code> is enabled. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>isSelected</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * Indicates whether this <code>Element</code> is selected. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>tagName</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * The tag name of this element. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>underlying</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * The underlying <code>WebElement</code> wrapped by this <code>Element</code>. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>attribute(name: String)</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * The attribute value of the given attribute name of this element, wrapped in a <code>Some</code>, or <code>None</code> if no * such attribute exists on this <code>Element</code>. * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>text</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * Returns the visible (<em>i.e.</em>, not hidden by CSS) text of this element, including sub-elements, without any leading or trailing whitespace. * </td> * </tr> * </table> * * <h2>Implicit wait</h2> * * <p> * To set Selenium's implicit wait timeout, you can call the <code>implicitlyWait</code> method: * </p> * * <pre class="stHighlight"> * implicitlyWait(Span(10, Seconds)) * </pre> * * <p> * Invoking this method sets the amount of time the driver will wait when searching for an element that is not immediately present. For * more information, see the documentation for method <code>implicitlyWait</code>. * </p> * * <h2>Page source and current URL</h2> * * <p> * It is possible to get the html source of currently loaded page, using: * </p> * * <pre class="stHighlight"> * pageSource * </pre> * * <p> * and if needed, get the current URL of currently loaded page: * </p> * * <pre class="stHighlight"> * currentUrl * </pre> * * <h2>Screen capture</h2> * * <p> * You can capture screen using the following code: * </p> * * <pre class="stHighlight"> * val file = capture * </pre> * * <p> * By default, the captured image file will be saved in temporary folder (returned by java.io.tmpdir property), with random file name * ends with .png extension. You can specify a fixed file name: * </p> * * <pre class="stHighlight"> * capture to "MyScreenShot.png" * </pre> * * <p> * or * </p> * * <pre class="stHighlight"> * capture to "MyScreenShot" * </pre> * * <p> * Both will result in a same file name <code>MyScreenShot.png</code>. * </p> * * <p> * You can also change the target folder screenshot file is written to, by saying: * </p> * * <pre class="stHighlight"> * setCaptureDir("/home/your_name/screenshots") * </pre> * * <p> * If you want to capture a screenshot when something goes wrong (e.g. test failed), you can use <code>withScreenshot</code>: * </p> * * <pre class="stHighlight"> * withScreenshot { * assert("Gold" == "Silver", "Expected gold, but got silver") * } * </pre> * * <p> * In case the test code fails, you'll see the screenshot location appended to the error message, for example: * </p> * * <pre class="stHighlight"> * Expected gold but got silver; screenshot capture in /tmp/AbCdEfGhIj.png * </pre> * * <a name="pageObjects"></a> * <h2>Using the page object pattern</h2> * * <p> * If you use the page object pattern, mixing trait <code>Page</code> into your page classes will allow you to use the <code>go to</code> * syntax with your page objects. Here's an example: * </p> * * <pre class="stHighlight"> * class HomePage extends Page { * val url = "http://localhost:9000/index.html" * } * * val homePage = new HomePage * go to homePage * </pre> * * <h2>Executing JavaScript</h2> * * <p> * To execute arbitrary JavaScript, for example, to test some JavaScript functions on your page, pass it to <code>executeScript</code>: * </p> * * <pre class="stHighlight"> * go to (host + "index.html") * val result1 = executeScript("return document.title;") * result1 should be ("Test Title") * val result2 = executeScript("return 'Hello ' + arguments[0]", "ScalaTest") * result2 should be ("Hello ScalaTest") * </pre> * * <p> * To execute an asynchronous bit of JavaScript, pass it to <code>executeAsyncScript</code>. You can set the script timeout with <code>setScriptTimeout</code>: * </p> * * <pre class="stHighlight"> * val script = """ * var callback = arguments[arguments.length - 1]; * window.setTimeout(function() {callback('Hello ScalaTest')}, 500); * """ * setScriptTimeout(1 second) * val result = executeAsyncScript(script) * result should be ("Hello ScalaTest") * </pre> * * <h2>Querying for elements</h2> * * <p> * You can query for arbitrary elements via <code>find</code> and <code>findAll</code>. The <code>find</code> method returns the first matching element, wrapped in a <code>Some</code>, * or <code>None</code> if no element is found. The <code>findAll</code> method returns an immutable <code>IndexedSeq</code> of all matching elements. If no elements match the query, <code>findAll</code> * returns an empty <code>IndexedSeq</code>. These methods allow you to perform rich queries using <code>for</code> expressions. Here are some examples: * </p> * * <pre class="stHighlight"> * val ele: Option[Element] = find("q") * * val eles: colection.immutable.IndexedSeq[Element] = findAll(className("small")) * for (e <- eles; if e.tagName != "input") * e should be ('displayed) * val textFields = eles filter { tf.isInstanceOf[TextField] } * </pre> * * <h2>Cleaning up</h2> * * <p> * To close the current browser window, and exit the driver if the current window was the only one remaining, use <code>close</code>: * </p> * * <pre class="stHighlight"> * close() * </pre> * * <p> * To close all windows, and exit the driver, use <code>quit</code>: * </p> * * <pre class="stHighlight"> * quit() * </pre> * * <a name="alternateForms"/> * <h2>Alternate forms</h2> * * <p> * Although statements like &ldquo;<code>delete all cookies</code>&rdquo; fit well with matcher statements * like &ldquo;<code>title should be ("Cheese!")</code>&rdquo;, they do not fit as well * with the simple method call form of assertions. If you prefer, you can avoid operator notation * and instead use alternatives that take the form of plain-old method calls. Here's an example: * </p> * * <pre class="stHighlight"> * goTo("http://www.google.com") * clickOn("q") * textField("q").value = "Cheese!" * submit() * // Google's search is rendered dynamically with JavaScript. * eventually(assert(pageTitle === "Cheese! - Google Search")) * </pre> * * <p> * Here's a table showing the complete list of alternatives: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>operator notation</strong></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>method call</strong></th></tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>go to (host + "index.html")</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>goTo(host + "index.html")</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>click on "aButton"</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>clickOn("aButton")</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>switch to activeElement</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>switchTo(activeElement)</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>add cookie ("cookie_name", "cookie_value")</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>addCookie("cookie_name", "cookie_value")</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>delete cookie "cookie_name"</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>deleteCookie("cookie_name")</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>delete all cookies</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>deleteAllCookies()</code> * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>capture to "MyScreenShot"</code> * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left"> * <code>captureTo("MyScreenShot")</code> * </td> * </tr> * </table> * * @author Chua Chee Seng * @author Bill Venners */ trait WebBrowser { /** * A point containing an XY screen location. */ case class Point(x: Int, y: Int) /** * A dimension containing the width and height of a screen element. */ case class Dimension(width: Int, height: Int) /** * Wrapper class for a Selenium <code>WebElement</code>. * * <p> * This class provides idiomatic Scala access to the services of an underlying <code>WebElement</code>. * You can access the wrapped <code>WebElement</code> via the <code>underlying</code> method. * </p> */ sealed trait Element { /** * The XY location of the top-left corner of this <code>Element</code>. * * <p> * This invokes <code>getLocation</code> on the underlying <code>WebElement</code>. * </p> * * @return the location of the top-left corner of this element on the page */ def location: Point = Point(underlying.getLocation.getX, underlying.getLocation.getY) /** * The width/height size of this <code>Element</code>. * * <p> * This invokes <code>getSize</code> on the underlying <code>WebElement</code>. * </p> * * @return the size of the element on the page */ def size: Dimension = Dimension(underlying.getSize.getWidth, underlying.getSize.getHeight) /** * Indicates whether this <code>Element</code> is displayed. * * <p> * This invokes <code>isDisplayed</code> on the underlying <code>WebElement</code>. * </p> * * @return <code>true</code> if the element is currently displayed */ def isDisplayed: Boolean = underlying.isDisplayed /** * Indicates whether this <code>Element</code> is enabled. * * <p> * This invokes <code>isEnabled</code> on the underlying <code>WebElement</code>, which * will generally return <code>true</code> for everything but disabled input elements. * </p> * * @return <code>true</code> if the element is currently enabled */ def isEnabled: Boolean = underlying.isEnabled /** * Indicates whether this <code>Element</code> is selected. * * <p> * This method, which invokes <code>isSelected</code> on the underlying <code>WebElement</code>, * is relevant only for input elements such as checkboxes, options in a single- or multiple-selection * list box, and radio buttons. For any other element it will simply return <code>false</code>. * </p> * * @return <code>true</code> if the element is currently selected or checked */ def isSelected: Boolean = underlying.isSelected /** * The tag name of this element. * * <p> * This method invokes <code>getTagName</code> on the underlying <code>WebElement</code>. * Note it returns the name of the tag, not the value of the of the <code>name</code> attribute. * For example, it will return will return <code>"input"</code> for the element * <code>&lt;input name="city" /&gt;</code>, not <code>"city"</code>. * </p> * * @return the tag name of this element */ def tagName: String = underlying.getTagName /** * The underlying <code>WebElement</code> wrapped by this <code>Element</code> */ val underlying: WebElement /** * The attribute value of the given attribute name of this element, wrapped in a <code>Some</code>, or <code>None</code> if no * such attribute exists on this <code>Element</code>. * * <p> * This method invokes <code>getAttribute</code> on the underlying <code>WebElement</code>, passing in the * specified <code>name</code>. * </p> * * @return the attribute with the given name, wrapped in a <code>Some</code>, else <code>None</code> */ def attribute(name: String): Option[String] = Option(underlying.getAttribute(name)) /** * Returns the visible (<em>i.e.</em>, not hidden by CSS) text of this element, including sub-elements, without any leading or trailing whitespace. * * @return the visible text enclosed by this element, or an empty string, if the element encloses no visible text */ def text: String = { val txt = underlying.getText if (txt != null) txt else "" // Just in case, I'm not sure if Selenium would ever return null here } /** * Returns the result of invoking <code>equals</code> on the underlying <code>Element</code>, passing * in the specified <code>other</code> object. * * @param other the object with which to compare for equality * * @return true if the passed object is equal to this one */ override def equals(other: Any): Boolean = underlying == other /** * Returns the result of invoking <code>hashCode</code> on the underlying <code>Element</code>. * * @return a hash code for this object */ override def hashCode: Int = underlying.hashCode /** * Returns the result of invoking <code>toString</code> on the underlying <code>Element</code>. * * @return a string representation of this object */ override def toString: String = underlying.toString } // fluentLinium has a doubleClick. Wonder how they are doing that? /** * Wrapper class for a Selenium <code>Cookie</code>. * * <p> * This class provides idiomatic Scala access to the services of an underlying <code>Cookie</code>. * You can access the wrapped <code>Cookie</code> via the <code>underlying</code> method. * </p> */ final class WrappedCookie(val underlying: Cookie) { /** * The domain to which this cookie is visible. * * <p> * This invokes <code>getDomain</code> on the underlying <code>Cookie</code>. * </p> * * @return the domain of this cookie */ def domain: String = underlying.getDomain /** * The expire date of this cookie. * * <p> * This invokes <code>getExpiry</code> on the underlying <code>Cookie</code>. * </p> * * @return the expire date of this cookie */ def expiry: Option[Date] = Option(underlying.getExpiry) /** * The name of this cookie. * * <p> * This invokes <code>getName</code> on the underlying <code>Cookie</code>. * </p> * * @return the name of this cookie */ def name: String = underlying.getName /** * The path of this cookie. * * <p> * This invokes <code>getPath</code> on the underlying <code>Cookie</code>. * </p> * * @return the path of this cookie */ def path: String = underlying.getPath /** * The value of this cookie. * * <p> * This invokes <code>getValue</code> on the underlying <code>Cookie</code>. * </p> * * @return the value of this cookie */ def value: String = underlying.getValue /** * Indicates whether the cookie requires a secure connection. * * <p> * This invokes <code>isSecure</code> on the underlying <code>Cookie</code>. * </p> * * @return true if this cookie requires a secure connection. */ def secure: Boolean = underlying.isSecure /** * Returns the result of invoking <code>equals</code> on the underlying <code>Cookie</code>, passing * in the specified <code>other</code> object. * * <p> * Two Selenium <code>Cookie</code>s are considered equal if their name and values are equal. * </p> * * @param other the object with which to compare for equality * * @return true if the passed object is equal to this one */ override def equals(other: Any): Boolean = underlying == other /** * Returns the result of invoking <code>hashCode</code> on the underlying <code>Cookie</code>. * * @return a hash code for this object */ override def hashCode: Int = underlying.hashCode /** * Returns the result of invoking <code>toString</code> on the underlying <code>Cookie</code>. * * @return a string representation of this object */ override def toString: String = underlying.toString } /** * This class is part of the ScalaTest's Selenium DSL. Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> * for an overview of the Selenium DSL. */ class CookiesNoun /** * This field supports cookie deletion in ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This field enables the following syntax: * </p> * * <pre class="stHighlight"> * delete all cookies * ^ * </pre> */ val cookies = new CookiesNoun /** * This sealed abstract class supports switching in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * One subclass of <code>SwitchTarget</code> exists for each kind of target that * can be switched to: active element, alert box, default content, frame (indentified by index, * name or id, or enclosed element), and window. * </p> */ sealed abstract class SwitchTarget[T] { /** * Abstract method implemented by subclasses that represent "targets" to which the user can switch. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): T } /** * This class supports switching to the currently active element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to activeElement * ^ * </pre> */ final class ActiveElementTarget extends SwitchTarget[Element] { /** * Switches the driver to the currently active element. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): Element = { createTypedElement(driver.switchTo.activeElement) } } /** * This class supports switching to the alert box in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to alertBox * ^ * </pre> */ final class AlertTarget extends SwitchTarget[Alert] { /** * Switches the driver to the currently active alert box. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): Alert = { driver.switchTo.alert } } /** * This class supports switching to the default content in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to defaultContent * ^ * </pre> */ final class DefaultContentTarget extends SwitchTarget[WebDriver] { /** * Switches the driver to the default content * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = { driver.switchTo.defaultContent } } /** * This class supports switching to a frame by index in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to frame(0) * ^ * </pre> */ final class FrameIndexTarget(index: Int) extends SwitchTarget[WebDriver] { /** * Switches the driver to the frame at the index that was passed to the constructor. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = try { driver.switchTo.frame(index) } catch { case e: org.openqa.selenium.NoSuchFrameException => throw new TestFailedException( sde => Some("Frame at index '" + index + "' not found."), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } /** * This class supports switching to a frame by name or ID in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to frame("name") * ^ * </pre> */ final class FrameNameOrIdTarget(nameOrId: String) extends SwitchTarget[WebDriver] { /** * Switches the driver to the frame with the name or ID that was passed to the constructor. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = try { driver.switchTo.frame(nameOrId) } catch { case e: org.openqa.selenium.NoSuchFrameException => throw new TestFailedException( sde => Some("Frame with name or ID '" + nameOrId + "' not found."), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } /** * This class supports switching to a frame by web element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. */ final class FrameWebElementTarget(webElement: WebElement) extends SwitchTarget[WebDriver] { /** * Switches the driver to the frame containing the <code>WebElement</code> that was passed to the constructor. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = try { driver.switchTo.frame(webElement) } catch { case e: org.openqa.selenium.NoSuchFrameException => throw new TestFailedException( sde => Some("Frame element '" + webElement + "' not found."), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } /** * This class supports switching to a frame by element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. */ final class FrameElementTarget(element: Element) extends SwitchTarget[WebDriver] { /** * Switches the driver to the frame containing the <code>Element</code> that was passed to the constructor. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = try { driver.switchTo.frame(element.underlying) } catch { case e: org.openqa.selenium.NoSuchFrameException => throw new TestFailedException( sde => Some("Frame element '" + element + "' not found."), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } /** * This class supports switching to a window by name or handle in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to window(windowHandle) * ^ * </pre> */ final class WindowTarget(nameOrHandle: String) extends SwitchTarget[WebDriver] { /** * Switches the driver to the window with the name or ID that was passed to the constructor. * * @param driver the <code>WebDriver</code> with which to perform the switch */ def switch(driver: WebDriver): WebDriver = try { driver.switchTo.window(nameOrHandle) } catch { case e: org.openqa.selenium.NoSuchWindowException => throw new TestFailedException( sde => Some("Window with nameOrHandle '" + nameOrHandle + "' not found."), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } private def isInputField(webElement: WebElement, name: String): Boolean = webElement.getTagName.toLowerCase == "input" && webElement.getAttribute("type").toLowerCase == name private def isTextField(webElement: WebElement): Boolean = isInputField(webElement, "text") private def isPasswordField(webElement: WebElement): Boolean = isInputField(webElement, "password") private def isCheckBox(webElement: WebElement): Boolean = isInputField(webElement, "checkbox") private def isRadioButton(webElement: WebElement): Boolean = isInputField(webElement, "radio") private def isEmailField(webElement: WebElement): Boolean = isInputField(webElement, "email") || isInputField(webElement, "text") private def isColorField(webElement: WebElement): Boolean = isInputField(webElement, "color") || isInputField(webElement, "text") private def isDateField(webElement: WebElement): Boolean = isInputField(webElement, "date") || isInputField(webElement, "text") private def isDateTimeField(webElement: WebElement): Boolean = isInputField(webElement, "datetime") || isInputField(webElement, "text") private def isDateTimeLocalField(webElement: WebElement): Boolean = isInputField(webElement, "datetime-local") || isInputField(webElement, "text") private def isMonthField(webElement: WebElement): Boolean = isInputField(webElement, "month") || isInputField(webElement, "text") private def isNumberField(webElement: WebElement): Boolean = isInputField(webElement, "number") || isInputField(webElement, "text") private def isRangeField(webElement: WebElement): Boolean = isInputField(webElement, "range") || isInputField(webElement, "text") private def isSearchField(webElement: WebElement): Boolean = isInputField(webElement, "search") || isInputField(webElement, "text") private def isTelField(webElement: WebElement): Boolean = isInputField(webElement, "tel") || isInputField(webElement, "text") private def isTimeField(webElement: WebElement): Boolean = isInputField(webElement, "time") || isInputField(webElement, "text") private def isUrlField(webElement: WebElement): Boolean = isInputField(webElement, "url") || isInputField(webElement, "text") private def isWeekField(webElement: WebElement): Boolean = isInputField(webElement, "week") || isInputField(webElement, "text") private def isTextArea(webElement: WebElement): Boolean = webElement.getTagName.toLowerCase == "textarea" /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * textField("q").value should be ("Cheese!") * </pre> * * @param underlying the <code>WebElement</code> representing a text field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a text field */ final class TextField(val underlying: WebElement) extends Element { if(!isTextField(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not text field."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Gets this text field's value. * * <p> * This method invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the text field's value */ def value: String = underlying.getAttribute("value") /** * Sets this text field's value. * * @param value the new value */ def value_=(value: String) { underlying.clear() underlying.sendKeys(value) } /** * Clears this text field. */ def clear() { underlying.clear() } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * textArea("q").value should be ("Cheese!") * </pre> * * @param underlying the <code>WebElement</code> representing a text area * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a text area */ final class TextArea(val underlying: WebElement) extends Element { if(!isTextArea(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not text area."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Gets this text area's value. * * <p> * This method invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the text area's value */ def value: String = underlying.getAttribute("value") /** * Sets this text area's value. * * @param value the new value */ def value_=(value: String) { underlying.clear() underlying.sendKeys(value) } /** * Clears this text area. */ def clear() { underlying.clear() } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * pwdField("q").value should be ("Cheese!") * </pre> * * @param underlying the <code>WebElement</code> representing a password field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a password field */ final class PasswordField(val underlying: WebElement) extends Element { if(!isPasswordField(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not password field."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Gets this password field's value. * * <p> * This method invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the password field's value */ def value: String = underlying.getAttribute("value") /** * Sets this password field's value. * * @param value the new value */ def value_=(value: String) { underlying.clear() underlying.sendKeys(value) } /** * Clears this text field. */ def clear() { underlying.clear() } } trait ValueElement extends Element { val underlying: WebElement def checkCorrectType(isA: (WebElement) => Boolean, typeDescription: String) = { if(!isA(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not " + typeDescription + " field."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) } /** * Gets this field's value. * * <p> * This method invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the field's value */ def value: String = underlying.getAttribute("value") /** * Sets this field's value. * * @param value the new value */ def value_=(value: String) { underlying.clear() underlying.sendKeys(value) } /** * Clears this field. */ def clear() { underlying.clear() } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * emailField("q").value should be ("foo@bar.com") * </pre> * * @param underlying the <code>WebElement</code> representing a email field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a email field */ final class EmailField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isEmailField, "email") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * colorField("q").value should be ("Cheese!") * </pre> * * @param underlying the <code>WebElement</code> representing a color field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a color field */ final class ColorField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isColorField, "color") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * dateField("q").value should be ("2003-03-01") * </pre> * * @param underlying the <code>WebElement</code> representing a date field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a date field */ final class DateField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isDateField, "date") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * dateTimeField("q").value should be ("2003-03-01T12:13:14") * </pre> * * @param underlying the <code>WebElement</code> representing a datetime field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a datetime field */ final class DateTimeField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isDateTimeField, "datetime") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * dateTimeLocalField("q").value should be ("2003-03-01T12:13:14") * </pre> * * @param underlying the <code>WebElement</code> representing a datetime-local field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a datetime-local field */ final class DateTimeLocalField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isDateTimeLocalField, "datetime-local") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * monthField("q").value should be ("2003-04") * </pre> * * @param underlying the <code>WebElement</code> representing a month field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a month field */ final class MonthField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isMonthField, "month") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * numberField("q").value should be ("1.3") * </pre> * * @param underlying the <code>WebElement</code> representing a number field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a number field */ final class NumberField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isNumberField, "number") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * rangeField("q").value should be ("1.3") * </pre> * * @param underlying the <code>WebElement</code> representing a range field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a range field */ final class RangeField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isRangeField, "range") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * searchField("q").value should be ("google") * </pre> * * @param underlying the <code>WebElement</code> representing a search field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a search field */ final class SearchField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isSearchField, "search") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * telField("q").value should be ("911-911-9191") * </pre> * * @param underlying the <code>WebElement</code> representing a tel field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a tel field */ final class TelField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isTelField, "tel") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * timeField("q").value should be ("12:13:14") * </pre> * * @param underlying the <code>WebElement</code> representing a time field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a time field */ final class TimeField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isTimeField, "time") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * urlField("q").value should be ("http://google.com") * </pre> * * @param underlying the <code>WebElement</code> representing a url field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a url field */ final class UrlField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isUrlField, "url") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * weekField("q").value should be ("1996-W16") * </pre> * * @param underlying the <code>WebElement</code> representing a week field * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a week field */ final class WeekField(val underlying: WebElement) extends Element with ValueElement { checkCorrectType(isWeekField, "week") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * radioButton(id("opt1")).value should be ("Option 1!") * </pre> * * @param underlying the <code>WebElement</code> representing a text area * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a text area */ final class RadioButton(val underlying: WebElement) extends Element { if(!isRadioButton(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not radio button."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Gets this radio button's value. * * <p> * Invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the radio button's value */ def value: String = underlying.getAttribute("value") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * radioButtonGroup("group1").value should be ("Option 2") * </pre> * * @throws TestFailedExeption if no radio button with the passed <code>groupName</code> are found */ final class RadioButtonGroup(groupName: String, driver: WebDriver) { private def groupElements = driver.findElements(By.name(groupName)).asScala.toList.filter(isRadioButton(_)) if (groupElements.length == 0) throw new TestFailedException( sde => Some("No radio buttons with group name '" + groupName + "' was found."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Returns the value of this group's selected radio button, or throws <code>TestFailedException</code> if no * radio button in this group is selected. * * @return the value of this group's selected radio button * @throws TestFailedExeption if no radio button in this group is selected */ def value: String = selection match { case Some(v) => v case None => throw new TestFailedException( sde => Some("The radio button group on which value was invoked contained no selected radio button."), None, getStackDepthFun("WebBrowser.scala", "value", 1) ) } /** * Returns the value of this group's selected radio button, wrapped in a <code>Some</code>, or <code>None</code>, if no * radio button in this group is selected. * * @return the value of this group's selected radio button, wrapped in a <code>Some</code>, else <code>None</code> */ def selection: Option[String] = { groupElements.find(_.isSelected) match { case Some(radio) => Some(radio.getAttribute("value")) case None => None } } /** * Selects the radio button with the passed value. * * @param the value of the radio button to select * @throws TestFailedExeption if the passed string is not the value of any radio button in this group */ def value_=(value: String) { groupElements.find(_.getAttribute("value") == value) match { case Some(radio) => radio.click() case None => throw new TestFailedException( sde => Some("Radio button value '" + value + "' not found for group '" + groupName + "'."), None, getStackDepthFun("WebBrowser.scala", "value_=", 1) ) } } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * checkbox("cbx1").select() * </pre> * * @param underlying the <code>WebElement</code> representing a checkbox * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a checkbox */ final class Checkbox(val underlying: WebElement) extends Element { if(!isCheckBox(underlying)) throw new TestFailedException( sde => Some("Element " + underlying + " is not check box."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Selects this checkbox. */ def select() { if (!underlying.isSelected) underlying.click() } /** * Clears this checkbox */ def clear() { if (underlying.isSelected()) underlying.click() } /** * Gets this checkbox's value. * * <p> * This method invokes <code>getAttribute("value")</code> on the underlying <code>WebElement</code>. * </p> * * @return the checkbox's value */ def value: String = underlying.getAttribute("value") } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * multiSel("select2").values += "option5" * ^ * </pre> * * <p> * Instances of this class are returned from the <code>values</code> method of <code>MultiSel</code>. * <code>MultiSelOptionSeq</code> is an immutable <code>IndexedSeq[String]</code> that wraps an underlying immutable <code>IndexedSeq[String]</code> and adds two * methods, <code>+</code> and <code>-</code>, to facilitate the <code>+=</code> syntax for setting additional options * of the <code>MultiSel</code>. The Scala compiler will rewrite: * </p> * * <pre class="stHighlight"> * multiSel("select2").values += "option5" * </pre> * * <p> * To: * </p> * * <pre class="stHighlight"> * multiSel("select2").values = multiSel("select2").values + "option5" * </pre> * * <p> * Thus, first a new <code>MultiSelOptionSeq</code> is created by invoking the <code>+</code> method on the <code>MultiSelOptionSeq</code> * returned by <code>values</code>, and that result is passed to the <code>values_=</code> method. * </p> * * <p> * For symmetry, this class also offers a <code>-</code> method, which can be used to deselect an option, like this: * </p> * * <pre class="stHighlight"> * multiSel("select2").values -= "option5" * ^ * </pre> * */ class MultiSelOptionSeq(underlying: collection.immutable.IndexedSeq[String]) extends collection.immutable.IndexedSeq[String] { /** * Selects an element by its index in the sequence. * * <p> * This method invokes <code>apply</code> on the underlying immutable <code>IndexedSeq[String]</code>, passing in <code>idx</code>, and returns the result. * </p> * * @param idx the index to select * @return the element of this sequence at index <code>idx</code>, where 0 indicates the first element */ def apply(idx: Int): String = underlying.apply(idx) /** * The length of this sequence. * * <p> * This method invokes <code>length</code> on the underlying immutable <code>IndexedSeq[String]</code> and returns the result. * </p> * * @return the number of elements in this sequence */ def length: Int = underlying.length /** * Appends a string element to this sequence, if it doesn't already exist in the sequence. * * <p> * If the string element already exists in this sequence, this method returns itself. If not, * this method returns a new <code>MultiSelOptionSeq</code> with the passed value appended to the * end of the original <code>MultiSelOptionSeq</code>. * </p> * * @param the string element to append to this sequence * @return a <code>MultiSelOptionSeq</code> that contains the passed string value */ def +(value: String): MultiSelOptionSeq = { if (!underlying.contains(value)) new MultiSelOptionSeq(underlying :+ value) else this } /** * Removes a string element to this sequence, if it already exists in the sequence. * * <p> * If the string element does not already exist in this sequence, this method returns itself. If the element * is contained in this sequence, this method returns a new <code>MultiSelOptionSeq</code> with the passed value * removed from the the original <code>MultiSelOptionSeq</code>, leaving any other elements in the same order. * </p> * * @param the string element to append to this sequence * @return a <code>MultiSelOptionSeq</code> that contains the passed string value */ def -(value: String): MultiSelOptionSeq = { if (underlying.contains(value)) new MultiSelOptionSeq(underlying.filter(_ != value)) else this } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * singleSel.clear() * </pre> * * @param underlying a <code>WebElement</code> representing a single selection list * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a single selection list */ class SingleSel(val underlying: WebElement) extends Element { if(underlying.getTagName.toLowerCase != "select") throw new TestFailedException( sde => Some("Element " + underlying + " is not select."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) private val select = new Select(underlying) if (select.isMultiple) throw new TestFailedException( sde => Some("Element " + underlying + " is not a single-selection list."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Returns the value of this single selection list, wrapped in a <code>Some</code>, or <code>None</code>, if this single * selection list has no currently selected value. * * @return the value of this single selection list, wrapped in a <code>Some</code>, else <code>None</code> */ def selection = { val first = select.getFirstSelectedOption if (first == null) None else Some(first.getAttribute("value")) } /** * Gets this single selection list's selected value, or throws <code>TestFailedException</code> if no value is currently selected. * * @return the single selection list's value * @throws TestFailedException if the single selection list has no selected value */ def value: String = selection match { case Some(v) => v case None => throw new TestFailedException( sde => Some("The single selection list on which value was invoked had no selection."), None, getStackDepthFun("WebBrowser.scala", "value", 1) ) } /** * Sets this single selection list's value to the passed value. * * @param value the new value * @throws TestFailedException if the passed value does not match not one of the single selection list's values */ def value_=(value : String) { try { select.selectByValue(value) } catch { case e: org.openqa.selenium.NoSuchElementException => throw new TestFailedException( sde => Some(e.getMessage), Some(e), getStackDepthFun("WebBrowser.scala", "value_=", 1) ) } } } /** * This class is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * multiSel("select2").clear("option5") * </pre> * * @param underlying a <code>WebElement</code> representing a multiple selection list * @throws TestFailedExeption if the passed <code>WebElement</code> does not represent a multiple selection list */ class MultiSel(val underlying: WebElement) extends Element { if(underlying.getTagName.toLowerCase != "select") throw new TestFailedException( sde => Some("Element " + underlying + " is not select."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) private val select = new Select(underlying) if (!select.isMultiple) throw new TestFailedException( sde => Some("Element " + underlying + " is not a multi-selection list."), None, getStackDepthFun("WebBrowser.scala", "this", 1) ) /** * Clears the passed value in this multiple selection list. * * @param value the value to clear */ def clear(value: String) { select.deselectByValue(value) } /** * Gets all selected values of this multiple selection list. * * <p> * If the multiple selection list has no selections, ths method will * return an empty <code>IndexedSeq</code>. * </p> * * @return An <code>IndexedSeq</code> containing the currently selected values */ def values: MultiSelOptionSeq = { val elementSeq = Vector.empty ++ select.getAllSelectedOptions.asScala new MultiSelOptionSeq(elementSeq.map(_.getAttribute("value"))) } /** * Clears any existing selections then sets all values contained in the passed <code>collection.Seq[String]</code>. * * <p> * In other words, the <code>values_=</code> method <em>replaces</em> the current selections, if any, with * new selections defined by the passed <code>Seq[String]</code>. * </p> * * @param values a <code>Seq</code> of string values to select * @throws TestFailedException if a value contained in the passed <code>Seq[String]</code> is not * among this multiple selection list's values. */ def values_=(values: collection.Seq[String]) { try { clearAll() values.foreach(select.selectByValue(_)) } catch { case e: org.openqa.selenium.NoSuchElementException => throw new TestFailedException( sde => Some(e.getMessage), Some(e), getStackDepthFun("WebBrowser.scala", "value_=", 1) ) } } /** * Clears all selected values in this multiple selection list. * * @param value the value to clear */ def clearAll() { select.deselectAll() } } /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * go to "http://www.artima.com" * ^ * </pre> */ object go { /** * Sends the browser to the passed URL. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * go to "http://www.artima.com" * ^ * </pre> * * @param url the URL to which to send the browser * @param driver the <code>WebDriver</code> with which to drive the browser */ def to(url: String)(implicit driver: WebDriver) { driver.get(url) } /** * Sends the browser to the URL contained in the passed <code>Page</code> object. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * go to homePage * ^ * </pre> * * @param page the <code>Page</code> object containing the URL to which to send the browser * @param driver the <code>WebDriver</code> with which to drive the browser */ def to(page: Page)(implicit driver: WebDriver) { driver.get(page.url) } } /** * Sends the browser to the passed URL. * * <p> * Here's an example: * </p> * * <pre class="stHighlight"> * goTo("http://www.artima.com") * </pre> * * @param url the URL to which to send the browser * @param driver the <code>WebDriver</code> with which to drive the browser */ def goTo(url: String)(implicit driver: WebDriver) { go to url } /** * Sends the browser to the URL contained in the passed <code>Page</code> object. * * <p> * Here's an example: * </p> * * <pre class="stHighlight"> * goTo(homePage) * </pre> * * @param page the <code>Page</code> object containing the URL to which to send the browser * @param driver the <code>WebDriver</code> with which to drive the browser */ def goTo(page: Page)(implicit driver: WebDriver) { go to page } /** * Closes the current browser window, and exits the driver if the current window was the only one remaining. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def close()(implicit driver: WebDriver) { driver.close() } /** * Returns the title of the current page, or the empty string if the current page has no title. * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the current page's title, or the empty string if the current page has no title */ def pageTitle(implicit driver: WebDriver): String = { val t = driver.getTitle if (t != null) t else "" } /** * Returns the source of the current page. * * <p> * This method invokes <code>getPageSource</code> on the passed <code>WebDriver</code> and returns the result. * </p> * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the source of the current page */ def pageSource(implicit driver: WebDriver): String = driver.getPageSource /** * Returns the URL of the current page. * * <p> * This method invokes <code>getCurrentUrl</code> on the passed <code>WebDriver</code> and returns the result. * </p> * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the URL of the current page */ def currentUrl(implicit driver: WebDriver): String = driver.getCurrentUrl /** * This trait is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * Subclasses of this trait define different ways of querying for elements, enabling * syntax such as the following: * </p> * * <pre class="stHighlight"> * click on id("q") * ^ * </pre> */ sealed trait Query { /** * The Selenium <code>By</code> for this query. */ val by: By /** * The query string for this query. * * <p> * For example, the query string for <code>id("q")</code> is <code>"q"</code>. * </p> */ val queryString: String /** * Returns the first <code>Element</code> selected by this query, or throws <code>TestFailedException</code> * if no <code>Element</code> is selected. * * <p> * The class of the <code>Element</code> returned will be a subtype of <code>Element</code> if appropriate. * For example, if this query selects a text field, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Element</code> selected by this query * @throws TestFailedException if nothing is selected by this query */ def element(implicit driver: WebDriver): Element = { try { createTypedElement(driver.findElement(by)) } catch { case e: org.openqa.selenium.NoSuchElementException => throw new TestFailedException( sde => Some("Element '" + queryString + "' not found."), Some(e), getStackDepthFun("WebBrowser.scala", "name", 1) ) } } /** * Returns the first <code>Element</code> selected by this query, wrapped in a <code>Some</code>, or <code>None</code> * if no <code>Element</code> is selected. * * <p> * The class of the <code>Element</code> returned will be a subtype of <code>Element</code> if appropriate. * For example, if this query selects a text field, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Element</code> selected by this query, wrapped in a <code>Some</code>, or <code>None</code> if * no <code>Element</code> is selected */ def findElement(implicit driver: WebDriver): Option[Element] = try { Some(createTypedElement(driver.findElement(by))) } catch { case e: org.openqa.selenium.NoSuchElementException => None } /** * Returns an <code>Iterator</code> over all <code>Element</code>s selected by this query. * * <p> * The class of the <code>Element</code>s produced by the returned <code>Iterator</code> will be a * subtypes of <code>Element</code> if appropriate. For example, if an <code>Element</code>representing * a text field is returned by the <code>Iterator</code>, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * <p> * If no <code>Elements</code> are selected by this query, this method will return an empty <code>Iterator</code> will be returned. * <p> * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Iterator</code> over all <code>Element</code>s selected by this query */ def findAllElements(implicit driver: WebDriver): Iterator[Element] = driver.findElements(by).asScala.toIterator.map { e => createTypedElement(e) } /** * Returns the first <code>WebElement</code> selected by this query, or throws <code>TestFailedException</code> * if no <code>WebElement</code> is selected. * * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>WebElement</code> selected by this query * @throws TestFailedException if nothing is selected by this query */ def webElement(implicit driver: WebDriver): WebElement = { try { driver.findElement(by) } catch { case e: org.openqa.selenium.NoSuchElementException => throw new TestFailedException( sde => Some("WebElement '" + queryString + "' not found."), Some(e), getStackDepthFun("WebBrowser.scala", "name", 1) ) } } } /** * An ID query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on id("q") * ^ * </pre> * * @param queryString the query string for this query. */ case class IdQuery(queryString: String) extends Query { val by = By.id(queryString)} /** * A name query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on name("q") * ^ * </pre> * * @param queryString the query string for this query. */ case class NameQuery(queryString: String) extends Query { val by = By.name(queryString) } /** * An XPath query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on xpath("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class XPathQuery(queryString: String) extends Query { val by = By.xpath(queryString) } // TODO: Are these case classes just to get at the val? /** * A class name query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on className("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class ClassNameQuery(queryString: String) extends Query { val by = By.className(queryString) } /** * A CSS selector query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on cssSelector("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class CssSelectorQuery(queryString: String) extends Query { val by = By.cssSelector(queryString) } /** * A link text query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on linkText("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class LinkTextQuery(queryString: String) extends Query { val by = By.linkText(queryString) } /** * A partial link text query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on partialLinkText("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class PartialLinkTextQuery(queryString: String) extends Query { val by = By.partialLinkText(queryString) } /** * A tag name query. * * <p> * This class enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on tagName("???") * ^ * </pre> * * @param queryString the query string for this query. */ case class TagNameQuery(queryString: String) extends Query { val by = By.tagName(queryString) } /** * Returns an ID query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on id("q") * ^ * </pre> * * @param queryString the query string for this query. */ def id(elementId: String): IdQuery = new IdQuery(elementId) /** * Returns a name query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on name("q") * ^ * </pre> * * @param queryString the query string for this query. */ def name(elementName: String): NameQuery = new NameQuery(elementName) /** * Returns an XPath query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on xpath("???") * ^ * </pre> * * @param queryString the query string for this query. */ def xpath(xpath: String): XPathQuery = new XPathQuery(xpath) /** * Returns a class name query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on className("???") * ^ * </pre> * * @param queryString the query string for this query. */ def className(className: String): ClassNameQuery = new ClassNameQuery(className) /** * Returns a CSS selector query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on cssSelector("???") * ^ * </pre> * * @param queryString the query string for this query. */ def cssSelector(cssSelector: String): CssSelectorQuery = new CssSelectorQuery(cssSelector) /** * Returns a link text query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on linkText("???") * ^ * </pre> * * @param queryString the query string for this query. */ def linkText(linkText: String): LinkTextQuery = new LinkTextQuery(linkText) /** * Returns a partial link text query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on partialLinkText("???") * ^ * </pre> * * @param queryString the query string for this query. */ def partialLinkText(partialLinkText: String): PartialLinkTextQuery = new PartialLinkTextQuery(partialLinkText) /** * Returns a tag name query. * * <p> * This method enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on tagName("???") * ^ * </pre> * * @param queryString the query string for this query. */ def tagName(tagName: String): TagNameQuery = new TagNameQuery(tagName) private def createTypedElement(element: WebElement): Element = { if (isTextField(element)) new TextField(element) else if (isTextArea(element)) new TextArea(element) else if (isPasswordField(element)) new PasswordField(element) else if (isEmailField(element)) new EmailField(element) else if (isColorField(element)) new ColorField(element) else if (isDateField(element)) new DateField(element) else if (isDateTimeField(element)) new DateTimeField(element) else if (isDateTimeLocalField(element)) new DateTimeLocalField(element) else if (isMonthField(element)) new MonthField(element) else if (isNumberField(element)) new NumberField(element) else if (isRangeField(element)) new RangeField(element) else if (isSearchField(element)) new SearchField(element) else if (isTelField(element)) new TelField(element) else if (isTimeField(element)) new TimeField(element) else if (isUrlField(element)) new UrlField(element) else if (isWeekField(element)) new WeekField(element) else if (isCheckBox(element)) new Checkbox(element) else if (isRadioButton(element)) new RadioButton(element) else if (element.getTagName.toLowerCase == "select") { val select = new Select(element) if (select.isMultiple) new MultiSel(element) else new SingleSel(element) } else new Element() { val underlying = element } } // XXX /** * Finds and returns the first element selected by the specified <code>Query</code>, wrapped * in a <code>Some</code>, or <code>None</code> if no element is selected. * * <p> * The class of the <code>Element</code> returned will be a subtype of <code>Element</code> if appropriate. * For example, if the query selects a text field, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Element</code> selected by this query, wrapped in a <code>Some</code>, or <code>None</code> if * no <code>Element</code> is selected */ def find(query: Query)(implicit driver: WebDriver): Option[Element] = query.findElement /** * Finds and returns the first element selected by the specified string ID or name, wrapped * in a <code>Some</code>, or <code>None</code> if no element is selected. YYY * * <p> * This method will try to lookup by id first. If it cannot find * any element with an id equal to the specified <code>queryString</code>, it will then try lookup by name. * </p> * * <p> * The class of the <code>Element</code> returned will be a subtype of <code>Element</code> if appropriate. * For example, if the query selects a text field, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Element</code> selected by this query, wrapped in a <code>Some</code>, or <code>None</code> if * no <code>Element</code> is selected */ def find(queryString: String)(implicit driver: WebDriver): Option[Element] = new IdQuery(queryString).findElement match { case Some(element) => Some(element) case None => new NameQuery(queryString).findElement match { case Some(element) => Some(element) case None => None } } /** * Returns an <code>Iterator</code> over all <code>Element</code>s selected by this query. * * <p> * The class of the <code>Element</code>s produced by the returned <code>Iterator</code> will be a * subtypes of <code>Element</code> if appropriate. For example, if an <code>Element</code>representing * a text field is returned by the <code>Iterator</code>, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * <p> * If no <code>Elements</code> are selected by this query, this method will return an empty <code>Iterator</code> will be returned. * <p> * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Iterator</code> over all <code>Element</code>s selected by this query */ def findAll(query: Query)(implicit driver: WebDriver): Iterator[Element] = query.findAllElements /** * Returns an <code>Iterator</code> over all <code>Element</code>s selected by the specified string ID or name * * <p> * This method will try to lookup by id first. If it cannot find * any element with an id equal to the specified <code>queryString</code>, it will then try lookup by name. * </p> * * <p> * The class of the <code>Element</code> returned will be a subtype of <code>Element</code> if appropriate. * For example, if the query selects a text field, the class of the returned <code>Element</code> will * be <code>TextField</code>. * </p> * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @return the <code>Iterator</code> over all <code>Element</code>s selected by this query */ def findAll(queryString: String)(implicit driver: WebDriver): Iterator[Element] = { val byIdItr = new IdQuery(queryString).findAllElements if (byIdItr.hasNext) byIdItr else new NameQuery(queryString).findAllElements } private def tryQueries[T](queryString: String)(f: Query => T)(implicit driver: WebDriver): T = { try { f(IdQuery(queryString)) } catch { case _: Throwable => f(NameQuery(queryString)) } } /** * Finds and returns the first <code>TextField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TextField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TextField</code> * @return the <code>TextField</code> selected by this query */ def textField(query: Query)(implicit driver: WebDriver): TextField = new TextField(query.webElement) /** * Finds and returns the first <code>TextField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TextField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TextField</code> * @return the <code>TextField</code> selected by this query */ def textField(queryString: String)(implicit driver: WebDriver): TextField = tryQueries(queryString)(q => new TextField(q.webElement)) /** * Finds and returns the first <code>TextArea</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TextArea</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TextArea</code> * @return the <code>TextArea</code> selected by this query */ def textArea(query: Query)(implicit driver: WebDriver) = new TextArea(query.webElement) /** * Finds and returns the first <code>TextArea</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TextArea</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TextArea</code> * @return the <code>TextArea</code> selected by this query */ def textArea(queryString: String)(implicit driver: WebDriver): TextArea = tryQueries(queryString)(q => new TextArea(q.webElement)) /** * Finds and returns the first <code>PasswordField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>PasswordField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>PasswordField</code> * @return the <code>PasswordField</code> selected by this query */ def pwdField(query: Query)(implicit driver: WebDriver): PasswordField = new PasswordField(query.webElement) /** * Finds and returns the first <code>PasswordField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>PasswordField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>PasswordField</code> * @return the <code>PasswordField</code> selected by this query */ def pwdField(queryString: String)(implicit driver: WebDriver): PasswordField = tryQueries(queryString)(q => new PasswordField(q.webElement)) /** * Finds and returns the first <code>EmailField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>EmailField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>EmailField</code> * @return the <code>EmailField</code> selected by this query */ def emailField(query: Query)(implicit driver: WebDriver): EmailField = new EmailField(query.webElement) /** * Finds and returns the first <code>EmailField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>EmailField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>EmailField</code> * @return the <code>EmailField</code> selected by this query */ def emailField(queryString: String)(implicit driver: WebDriver): EmailField = tryQueries(queryString)(q => new EmailField(q.webElement)) /** * Finds and returns the first <code>ColorField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>ColorField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>ColorField</code> * @return the <code>ColorField</code> selected by this query */ def colorField(query: Query)(implicit driver: WebDriver): ColorField = new ColorField(query.webElement) /** * Finds and returns the first <code>ColorField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>ColorField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>ColorField</code> * @return the <code>ColorField</code> selected by this query */ def colorField(queryString: String)(implicit driver: WebDriver): ColorField = tryQueries(queryString)(q => new ColorField(q.webElement)) /** * Finds and returns the first <code>DateField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateField</code> * @return the <code>DateField</code> selected by this query */ def dateField(query: Query)(implicit driver: WebDriver): DateField = new DateField(query.webElement) /** * Finds and returns the first <code>DateField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateField</code> * @return the <code>DateField</code> selected by this query */ def dateField(queryString: String)(implicit driver: WebDriver): DateField = tryQueries(queryString)(q => new DateField(q.webElement)) /** * Finds and returns the first <code>DateTimeField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateTimeField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateTimeField</code> * @return the <code>DateTimeField</code> selected by this query */ def dateTimeField(query: Query)(implicit driver: WebDriver): DateTimeField = new DateTimeField(query.webElement) /** * Finds and returns the first <code>DateTimeField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateTimeField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateTimeField</code> * @return the <code>DateTimeField</code> selected by this query */ def dateTimeField(queryString: String)(implicit driver: WebDriver): DateTimeField = tryQueries(queryString)(q => new DateTimeField(q.webElement)) /** * Finds and returns the first <code>DateTimeLocalField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateTimeLocalField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateTimeLocalField</code> * @return the <code>DateTimeLocalField</code> selected by this query */ def dateTimeLocalField(query: Query)(implicit driver: WebDriver): DateTimeLocalField = new DateTimeLocalField(query.webElement) /** * Finds and returns the first <code>DateTimeLocalField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>DateTimeLocalField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>DateTimeLocalField</code> * @return the <code>DateTimeLocalField</code> selected by this query */ def dateTimeLocalField(queryString: String)(implicit driver: WebDriver): DateTimeLocalField = tryQueries(queryString)(q => new DateTimeLocalField(q.webElement)) /** * Finds and returns the first <code>MonthField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>MonthField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>MonthField</code> * @return the <code>MonthField</code> selected by this query */ def monthField(query: Query)(implicit driver: WebDriver): MonthField = new MonthField(query.webElement) /** * Finds and returns the first <code>MonthField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>MonthField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>MonthField</code> * @return the <code>MonthField</code> selected by this query */ def monthField(queryString: String)(implicit driver: WebDriver): MonthField = tryQueries(queryString)(q => new MonthField(q.webElement)) /** * Finds and returns the first <code>NumberField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>NumberField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>NumberField</code> * @return the <code>NumberField</code> selected by this query */ def numberField(query: Query)(implicit driver: WebDriver): NumberField = new NumberField(query.webElement) /** * Finds and returns the first <code>NumberField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>NumberField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>NumberField</code> * @return the <code>NumberField</code> selected by this query */ def numberField(queryString: String)(implicit driver: WebDriver): NumberField = tryQueries(queryString)(q => new NumberField(q.webElement)) /** * Finds and returns the first <code>RangeField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>RangeField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>RangeField</code> * @return the <code>RangeField</code> selected by this query */ def rangeField(query: Query)(implicit driver: WebDriver): RangeField = new RangeField(query.webElement) /** * Finds and returns the first <code>RangeField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>RangeField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>RangeField</code> * @return the <code>RangeField</code> selected by this query */ def rangeField(queryString: String)(implicit driver: WebDriver): RangeField = tryQueries(queryString)(q => new RangeField(q.webElement)) /** * Finds and returns the first <code>SearchField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>SearchField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>SearchField</code> * @return the <code>SearchField</code> selected by this query */ def searchField(query: Query)(implicit driver: WebDriver): SearchField = new SearchField(query.webElement) /** * Finds and returns the first <code>SearchField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>SearchField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>SearchField</code> * @return the <code>SearchField</code> selected by this query */ def searchField(queryString: String)(implicit driver: WebDriver): SearchField = tryQueries(queryString)(q => new SearchField(q.webElement)) /** * Finds and returns the first <code>TelField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TelField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TelField</code> * @return the <code>TelField</code> selected by this query */ def telField(query: Query)(implicit driver: WebDriver): TelField = new TelField(query.webElement) /** * Finds and returns the first <code>TelField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TelField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TelField</code> * @return the <code>TelField</code> selected by this query */ def telField(queryString: String)(implicit driver: WebDriver): TelField = tryQueries(queryString)(q => new TelField(q.webElement)) /** * Finds and returns the first <code>TimeField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TimeField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TimeField</code> * @return the <code>TimeField</code> selected by this query */ def timeField(query: Query)(implicit driver: WebDriver): TimeField = new TimeField(query.webElement) /** * Finds and returns the first <code>TimeField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>TimeField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>TimeField</code> * @return the <code>TimeField</code> selected by this query */ def timeField(queryString: String)(implicit driver: WebDriver): TimeField = tryQueries(queryString)(q => new TimeField(q.webElement)) /** * Finds and returns the first <code>UrlField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>UrlField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>UrlField</code> * @return the <code>UrlField</code> selected by this query */ def urlField(query: Query)(implicit driver: WebDriver): UrlField = new UrlField(query.webElement) /** * Finds and returns the first <code>UrlField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>UrlField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>UrlField</code> * @return the <code>UrlField</code> selected by this query */ def urlField(queryString: String)(implicit driver: WebDriver): UrlField = tryQueries(queryString)(q => new UrlField(q.webElement)) /** * Finds and returns the first <code>WeekField</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>WeekField</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>WeekField</code> * @return the <code>WeekField</code> selected by this query */ def weekField(query: Query)(implicit driver: WebDriver): WeekField = new WeekField(query.webElement) /** * Finds and returns the first <code>WeekField</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>WeekField</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>WeekField</code> * @return the <code>WeekField</code> selected by this query */ def weekField(queryString: String)(implicit driver: WebDriver): WeekField = tryQueries(queryString)(q => new WeekField(q.webElement)) /** * Finds and returns <code>RadioButtonGroup</code> selected by the specified group name, throws <code>TestFailedException</code> if * no element with the specified group name is found, or found any element with the specified group name but not a <code>RadioButton</code> * * @param groupName the group name with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if no element with the specified group name is found, or found any element with the specified group name but not a <code>RadioButton</code> * @return the <code>RadioButtonGroup</code> selected by this query */ def radioButtonGroup(groupName: String)(implicit driver: WebDriver) = new RadioButtonGroup(groupName, driver) /** * Finds and returns the first <code>RadioButton</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>RadioButton</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>RadioButton</code> * @return the <code>RadioButton</code> selected by this query */ def radioButton(query: Query)(implicit driver: WebDriver) = new RadioButton(query.webElement) /** * Finds and returns the first <code>RadioButton</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>RadioButton</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>RadioButton</code> * @return the <code>RadioButton</code> selected by this query */ def radioButton(queryString: String)(implicit driver: WebDriver): RadioButton = tryQueries(queryString)(q => new RadioButton(q.webElement)) /** * Finds and returns the first <code>Checkbox</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>Checkbox</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>Checkbox</code> * @return the <code>Checkbox</code> selected by this query */ def checkbox(query: Query)(implicit driver: WebDriver) = new Checkbox(query.webElement) /** * Finds and returns the first <code>Checkbox</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>Checkbox</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>Checkbox</code> * @return the <code>Checkbox</code> selected by this query */ def checkbox(queryString: String)(implicit driver: WebDriver): Checkbox = tryQueries(queryString)(q => new Checkbox(q.webElement)) /** * Finds and returns the first <code>SingleSel</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>SingleSel</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>SingleSel</code> * @return the <code>SingleSel</code> selected by this query */ def singleSel(query: Query)(implicit driver: WebDriver) = new SingleSel(query.webElement) /** * Finds and returns the first <code>SingleSel</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>SingleSel</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>SingleSel</code> * @return the <code>SingleSel</code> selected by this query */ def singleSel(queryString: String)(implicit driver: WebDriver): SingleSel = tryQueries(queryString)(q => new SingleSel(q.webElement)) /** * Finds and returns the first <code>MultiSel</code> selected by the specified <code>Query</code>, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>MultiSel</code>. * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>MultiSel</code> * @return the <code>MultiSel</code> selected by this query */ def multiSel(query: Query)(implicit driver: WebDriver) = new MultiSel(query.webElement) /** * Finds and returns the first <code>MultiSel</code> selected by the specified string ID or name, throws <code>TestFailedException</code> * if element not found or the found element is not a <code>MultiSel</code>. * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if element not found or found element is not a <code>MultiSel</code> * @return the <code>MultiSel</code> selected by this query */ def multiSel(queryString: String)(implicit driver: WebDriver): MultiSel = tryQueries(queryString)(q => new MultiSel(q.webElement)) /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * click on "aButton" * ^ * </pre> */ object click { /** * Click on the specified <code>WebElement</code> * * @param element the <code>WebElement</code> to click on */ def on(element: WebElement) { element.click() } /** * Click on the first <code>Element</code> selected by the specified <code>Query</code> * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser */ def on(query: Query)(implicit driver: WebDriver) { query.webElement.click() } /** * Click on the first <code>Element</code> selected by the specified string ID or name * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser */ def on(queryString: String)(implicit driver: WebDriver) { // stack depth is not correct if just call the button("...") directly. val target = tryQueries(queryString)(q => q.webElement) on(target) } /** * Click on the specified <code>Element</code> * * @param element the <code>Element</code> to click on */ def on(element: Element) { element.underlying.click() } } /** * Click on the specified <code>WebElement</code> * * @param element the <code>WebElement</code> to click on */ def clickOn(element: WebElement) { click on element } /** * Click on the first <code>Element</code> selected by the specified <code>Query</code> * * @param query the <code>Query</code> with which to search * @param driver the <code>WebDriver</code> with which to drive the browser */ def clickOn(query: Query)(implicit driver: WebDriver) { click on query } /** * Click on the first <code>Element</code> selected by the specified string ID or name * * @param queryString the string with which to search, first by ID then by name * @param driver the <code>WebDriver</code> with which to drive the browser */ def clickOn(queryString: String)(implicit driver: WebDriver) { click on queryString } /** * Click on the specified <code>Element</code> * * @param element the <code>Element</code> to click on */ def clickOn(element: Element) { click on element } /** * Submit the form where current active element belongs to, and throws TestFailedException if current active element is not * in a form or underlying WebDriver encounters problem when submitting the form. If this causes the current page to change, * this call will block until the new page is loaded. * * @param driver the <code>WebDriver</code> with which to drive the browser * @throws TestFailedException if current active element is not in a form or underlying WebDriver encounters problem when submitting the form. */ def submit()(implicit driver: WebDriver) { try { (switch to activeElement).underlying.submit() } catch { case e: org.openqa.selenium.NoSuchElementException => throw new TestFailedException( sde => Some("Current element is not a form element."), Some(e), getStackDepthFun("WebBrowser.scala", "name", 1) ) case e: Throwable => // Could happens as bug in different WebDriver, like NullPointerException in HtmlUnitDriver when element is not a form element. // Anyway, we'll just wrap them as TestFailedException throw new TestFailedException( sde => Some("WebDriver encountered problem to submit(): " + e.getMessage), Some(e), getStackDepthFun("WebBrowser.scala", "submit", 0) ) } } /** * Sets the amount of time the driver should wait when searching for an element that is not immediately present. * * <p> * When searching for requested elements, Selenium will poll the page until the requested element (or at least one of multiple requested * elements) is found or this "implicit wait" timeout has expired. * If the timeout expires, Selenium will throw <code>NoSuchElementException</code>, which ScalaTest's Selenium DSL will wrap in a <code>TestFailedException</code>. * </p> * * <p> * You can alternatively set this timeout to zero and use ScalaTest's <code>eventually</code> construct. * </p> * * <p> * This method invokes <code>manage.timeouts.implicitlyWait</code> on the passed <code>WebDriver</code>. See the documentation of Selenium's * <code>WebDriver#Timeouts</code> interface for more information. * </p> * * @param timeout the time span to implicitly wait * @param driver the <code>WebDriver</code> on which to set the implicit wait */ def implicitlyWait(timeout: Span)(implicit driver: WebDriver) { driver.manage.timeouts.implicitlyWait(timeout.totalNanos, TimeUnit.NANOSECONDS) } /** * Close all windows, and exit the driver. * * @param driver the <code>WebDriver</code> on which to quit. */ def quit()(implicit driver: WebDriver) { driver.quit() } /** * Get an opaque handle to current active window that uniquely identifies it within the implicit driver instance. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def windowHandle(implicit driver: WebDriver): String = driver.getWindowHandle /** * Get a set of window handles which can be used to iterate over all open windows * * @param driver the <code>WebDriver</code> with which to drive the browser */ def windowHandles(implicit driver: WebDriver): Set[String] = driver.getWindowHandles.asScala.toSet /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * switch to alertBox * ^ * </pre> */ object switch { /** * Switch to the specified <code>SwitchTarget</code> * * @param target the <code>SwitchTarget</code> to switch to * @param driver the <code>WebDriver</code> with which to drive the browser * @return instance of specified <code>SwitchTarget</code>'s type parameter */ def to[T](target: SwitchTarget[T])(implicit driver: WebDriver): T = { target.switch(driver) } } /** * This value supports switching to the currently active element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to activeElement * ^ * </pre> */ val activeElement = new ActiveElementTarget() /** * This value supports switching to the alert box in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to alertBox * ^ * </pre> */ val alertBox = new AlertTarget() /** * This value supports switching to the default content in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to defaultContent * ^ * </pre> */ val defaultContent = new DefaultContentTarget() /** * This method supports switching to a frame by index in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to frame(0) * ^ * </pre> * * @param index the index of frame to switch to * @return a FrameIndexTarget instance */ def frame(index: Int) = new FrameIndexTarget(index) /** * This method supports switching to a frame by name or ID in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to frame("name") * ^ * </pre> * * @param nameOrId name or ID of the frame to switch to * @return a FrameNameOrIdTarget instance */ def frame(nameOrId: String) = new FrameNameOrIdTarget(nameOrId) /** * This method supports switching to a frame by web element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * @param element <code>WebElement</code> which is contained in the frame to switch to * @return a FrameWebElementTarget instance */ def frame(element: WebElement) = new FrameWebElementTarget(element) /** * This method supports switching to a frame by element in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * @param element <code>Element</code> which is contained in the frame to switch to * @return a FrameElementTarget instance */ def frame(element: Element) = new FrameElementTarget(element) /** * This method supports switching to a frame by <code>Query</code> in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * @param query <code>Query</code> used to select <code>WebElement</code> which is contained in the frame to switch to * @return a FrameWebElementTarget instance */ def frame(query: Query)(implicit driver: WebDriver) = new FrameWebElementTarget(query.webElement) /** * This class supports switching to a window by name or handle in ScalaTest's Selenium DSL. * Please see the documentation for <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This class is enables the following syntax: * </p> * * <pre> * switch to window(windowHandle) * ^ * </pre> * * @param nameOrHandle name or window handle of the window to switch to * @return a WindowTarget instance */ def window(nameOrHandle: String) = new WindowTarget(nameOrHandle) /** * Switch to the specified <code>SwitchTarget</code> * * @param target the <code>SwitchTarget</code> to switch to * @param driver the <code>WebDriver</code> with which to drive the browser * @return instance of specified <code>SwitchTarget</code>'s type parameter */ def switchTo[T](target: SwitchTarget[T])(implicit driver: WebDriver): T = switch to target /** * Go back to previous page. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def goBack()(implicit driver: WebDriver) { driver.navigate.back() } /** * Go forward to next page. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def goForward()(implicit driver: WebDriver) { driver.navigate.forward() } /** * Reload the current page. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def reloadPage()(implicit driver: WebDriver) { driver.navigate.refresh() } /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * add cookie("aName", "aValue") * ^ * </pre> */ object add { private def addCookie(cookie: Cookie)(implicit driver: WebDriver) { driver.manage.addCookie(cookie) } // Default values determined from http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/Cookie.java /** * Add cookie in the web browser. If the cookie's domain name is left blank (default), it is assumed that the cookie is meant for the domain of the current document. * * @param name cookie's name * @param value cookie's value * @param path cookie's path * @param expiry cookie's expiry data * @param domain cookie's domain name * @param secure whether this cookie is secured. * @param driver the <code>WebDriver</code> with which to drive the browser */ def cookie(name: String, value: String, path: String = "/", expiry: Date = null, domain: String = null, secure: Boolean = false)(implicit driver: WebDriver) { addCookie(new Cookie(name, value, domain, path, expiry, secure)) } } /** * Get a saved cookie from web browser, throws TestFailedException if the cookie does not exist. * * @param name cookie's name * @return a WrappedCookie instance */ def cookie(name: String)(implicit driver: WebDriver): WrappedCookie = { getCookie(name) } private def getCookie(name: String)(implicit driver: WebDriver): WrappedCookie = { driver.manage.getCookies.asScala.toList.find(_.getName == name) match { case Some(cookie) => new WrappedCookie(cookie) case None => throw new TestFailedException( sde => Some("Cookie '" + name + "' not found."), None, getStackDepthFun("WebBrowser.scala", "getCookie", 1) ) } } /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * delete cookie "aName" * ^ * * delete all cookies * ^ * </pre> */ object delete { private def deleteCookie(name: String)(implicit driver: WebDriver) { val cookie = getCookie(name) if (cookie == null) throw new TestFailedException( sde => Some("Cookie '" + name + "' not found."), None, getStackDepthFun("WebBrowser.scala", "deleteCookie", 1) ) driver.manage.deleteCookie(cookie.underlying) } /** * Delete cookie with the specified name from web browser, throws TestFailedException if the specified cookie does not exists. * * @param name cookie's name * @param driver the <code>WebDriver</code> with which to drive the browser */ def cookie(name: String)(implicit driver: WebDriver) { deleteCookie(name) } /** * Delete all cookies in the current domain from web browser. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def all(cookies: CookiesNoun)(implicit driver: WebDriver) { driver.manage.deleteAllCookies() } } /** * Add cookie in the web browser. If the cookie's domain name is left blank (default), it is assumed that the cookie is meant for the domain of the current document. * * @param name cookie's name * @param value cookie's value * @param path cookie's path * @param expiry cookie's expiry data * @param domain cookie's domain name * @param secure whether this cookie is secured. * @param driver the <code>WebDriver</code> with which to drive the browser */ def addCookie(name: String, value: String, path: String = "/", expiry: Date = null, domain: String = null, secure: Boolean = false)(implicit driver: WebDriver) { add cookie (name, value, path, expiry, domain, secure) } /** * Delete cookie with the specified name from web browser, throws TestFailedException if the specified cookie does not exists. * * @param name cookie's name * @param driver the <code>WebDriver</code> with which to drive the browser */ def deleteCookie(name: String)(implicit driver: WebDriver) { delete cookie name } /** * Delete all cookies in the current domain from web browser. * * @param driver the <code>WebDriver</code> with which to drive the browser */ def deleteAllCookies()(implicit driver: WebDriver) { delete all cookies } /** * Check if screenshot is supported * * @param driver the <code>WebDriver</code> with which to drive the browser * @return true if screenshot is supported, false otherwise */ def isScreenshotSupported(implicit driver: WebDriver): Boolean = driver.isInstanceOf[TakesScreenshot] /** * This object is part of ScalaTest's Selenium DSL. Please see the documentation for * <a href="WebBrowser.html"><code>WebBrowser</code></a> for an overview of the Selenium DSL. * * <p> * This object enables syntax such as the following: * </p> * * <pre class="stHighlight"> * capture * ^ * * capture to "MyScreenshot.png" * ^ * </pre> */ object capture { /** * Capture screenshot and save it as the specified name (if file name does not end with .png, it will be extended automatically) in capture directory, * which by default is system property's java.io.tmpdir. You can change capture directory by calling <code>setCaptureDir</code> * * @param fileName screenshot file name, if does not end with .png, it will be extended automatically */ def to(fileName: String)(implicit driver: WebDriver) { driver match { case takesScreenshot: TakesScreenshot => val tmpFile = takesScreenshot.getScreenshotAs(OutputType.FILE) val outFile = new File(targetDir, if (fileName.toLowerCase.endsWith(".png")) fileName else fileName + ".png") new FileOutputStream(outFile).getChannel.transferFrom( new FileInputStream(tmpFile).getChannel, 0, Long.MaxValue) case _ => throw new UnsupportedOperationException("Screen capture is not support by " + driver.getClass.getName) } } /** * Capture screenshot and save it in capture directory, which by default is system property's java.io.tmpdir. * You can change capture directory by calling <code>setCaptureDir</code> */ def apply()(implicit driver: WebDriver): File = { driver match { case takesScreenshot: TakesScreenshot => val tmpFile = takesScreenshot.getScreenshotAs(OutputType.FILE) val fileName = tmpFile.getName val outFile = new File(targetDir, if (fileName.toLowerCase.endsWith(".png")) fileName else fileName + ".png") new FileOutputStream(outFile).getChannel.transferFrom( new FileInputStream(tmpFile).getChannel, 0, Long.MaxValue) outFile case _ => throw new UnsupportedOperationException("Screen capture is not support by " + driver.getClass.getName) } } } /** * Capture screenshot and save it as the specified name (if file name does not end with .png, it will be extended automatically) in capture directory, * which by default is system property's java.io.tmpdir. You can change capture directory by calling <code>setCaptureDir</code> * * @param fileName screenshot file name, if does not end with .png, it will be extended automatically */ def captureTo(fileName: String)(implicit driver: WebDriver) { capture to fileName } // Can get by with volatile, because the setting doesn't depend on the getting @volatile private var targetDir = new File(System.getProperty("java.io.tmpdir")) /** * Set capture directory. * * @param targetDirPath the path of capture directory */ def setCaptureDir(targetDirPath: String) { targetDir = if (targetDirPath.endsWith(File.separator)) new File(targetDirPath) else new File(targetDirPath + File.separator) if (!targetDir.exists) targetDir.mkdirs() } /** * Execute the given function, if <code>ModifiableMessage</code> exception is thrown from the given function, * a screenshot will be captured automatically into capture directory, which by default is system property's java.io.tmpdir. * You can change capture directory by calling <code>setCaptureDir</code> * * @param fun function to execute */ def withScreenshot(fun: => Unit)(implicit driver: WebDriver) { try { fun } catch { case e: org.scalatest.exceptions.ModifiableMessage[_] => throw e.modifyMessage{ (currentMessage: Option[String]) => val captureFile: File = capture.apply() currentMessage match { case Some(currentMsg) => Some(currentMsg + "; screenshot captured in " + captureFile.getAbsolutePath) case None => Some("screenshot captured in " + captureFile.getAbsolutePath) } } } } /** * Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function. * * <p> * Within the script, you can use <code>document</code> to refer to the current document. Local variables will not be available once the script has finished executing, but global variables will. * </p> * * <p> * To return a value (e.g. if the script contains a return statement), then the following steps will be taken: * </p> * * <ol> * <li>For an HTML element, this method returns a WebElement</li> * <li>For a decimal, a Double is returned</li> * <li>For a non-decimal number, a Long is returned</li> * <li>For a boolean, a Boolean is returned</li> * <li>For all other cases, a String is returned</li> * <li>For an array, return a List<Object> with each object following the rules above. We support nested lists</li> * <li>Unless the value is null or there is no return value, in which null is returned</li> * </ol> * * <p> * Script arguments must be a number, boolean, String, WebElement, or a List of any combination of these. An exception will * be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the "arguments" variable. * (Note that although this behavior is specified by <a href="http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html">Selenium's JavascriptExecutor Javadoc</a>, * it may still be possible for the underlying <code>JavascriptExecutor</code> implementation to return an objects of other types. * For example, <code>HtmlUnit</code> has been observed to return a <code>java.util.Map</code> for a Javascript object.) * </p> * * @param script the JavaScript to execute * @param args the arguments to the script, may be empty * @return One of Boolean, Long, String, List or WebElement. Or null (following <a href="http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html">Selenium's JavascriptExecutor Javadoc</a>) */ def executeScript[T](script: String, args: AnyRef*)(implicit driver: WebDriver): AnyRef = driver match { case executor: JavascriptExecutor => executor.executeScript(script, args.toArray : _*) case _ => throw new UnsupportedOperationException("Web driver " + driver.getClass.getName + " does not support javascript execution.") } /** * Executes an asynchronous piece of JavaScript in the context of the currently selected frame or window. Unlike executing synchronous JavaScript, * scripts executed with this method must explicitly signal they are finished by invoking the provided callback. This callback is always injected into * the executed function as the last argument. * * <p> * The first argument passed to the callback function will be used as the script's result. This value will be handled as follows: * </p> * * <ol> * <li>For an HTML element, this method returns a WebElement</li> * <li>For a number, a Long is returned</li> * <li>For a boolean, a Boolean is returned</li> * <li>For all other cases, a String is returned</li> * <li>For an array, return a List<Object> with each object following the rules above. We support nested lists</li> * <li>Unless the value is null or there is no return value, in which null is returned</li> * </ol> * * <p> * Script arguments must be a number, boolean, String, WebElement, or a List of any combination of these. An exception will * be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the "arguments" variable. * (Note that although this behavior is specified by <a href="http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html">Selenium's JavascriptExecutor Javadoc</a>, * it may still be possible for the underlying <code>JavascriptExecutor</code> implementation to return an objects of other types. * For example, <code>HtmlUnit</code> has been observed to return a <code>java.util.Map</code> for a Javascript object.) * </p> * * @param script the JavaScript to execute * @param args the arguments to the script, may be empty * @return One of Boolean, Long, String, List, WebElement, or null (following <a href="http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html">Selenium's JavascriptExecutor Javadoc</a>) */ def executeAsyncScript(script: String, args: AnyRef*)(implicit driver: WebDriver): AnyRef = driver match { case executor: JavascriptExecutor => executor.executeAsyncScript(script, args.toArray : _*) case _ => throw new UnsupportedOperationException("Web driver " + driver.getClass.getName + " does not support javascript execution.") } /** * Sets the amount of time to wait for an asynchronous script to finish execution before throwing an exception. * * @param timeout the amount of time to wait for an asynchronous script to finish execution before throwing exception */ def setScriptTimeout(timeout: Span)(implicit driver: WebDriver) { driver.manage().timeouts().setScriptTimeout(timeout.totalNanos, TimeUnit.NANOSECONDS); } private def getStackDepthFun(fileName: String, methodName: String, adjustment: Int = 0): (StackDepthException => Int) = { sde => getStackDepth(sde.getStackTrace, fileName, methodName, adjustment) } private def getStackDepth(stackTrace: Array[StackTraceElement], fileName: String, methodName: String, adjustment: Int = 0) = { val stackTraceList = stackTrace.toList val fileNameIsDesiredList: List[Boolean] = for (element <- stackTraceList) yield element.getFileName == fileName // such as "Checkers.scala" val methodNameIsDesiredList: List[Boolean] = for (element <- stackTraceList) yield element.getMethodName == methodName // such as "check" // For element 0, the previous file name was not desired, because there is no previous // one, so you start with false. For element 1, it depends on whether element 0 of the stack trace // had the desired file name, and so forth. val previousFileNameIsDesiredList: List[Boolean] = false :: (fileNameIsDesiredList.dropRight(1)) // Zip these two related lists together. They now have two boolean values together, when both // are true, that's a stack trace element that should be included in the stack depth. val zipped1 = methodNameIsDesiredList zip previousFileNameIsDesiredList val methodNameAndPreviousFileNameAreDesiredList: List[Boolean] = for ((methodNameIsDesired, previousFileNameIsDesired) <- zipped1) yield methodNameIsDesired && previousFileNameIsDesired // Zip the two lists together, that when one or the other is true is an include. val zipped2 = fileNameIsDesiredList zip methodNameAndPreviousFileNameAreDesiredList val includeInStackDepthList: List[Boolean] = for ((fileNameIsDesired, methodNameAndPreviousFileNameAreDesired) <- zipped2) yield fileNameIsDesired || methodNameAndPreviousFileNameAreDesired val includeDepth = includeInStackDepthList.takeWhile(include => include).length val depth = if (includeDepth == 0 && stackTrace(0).getFileName != fileName && stackTrace(0).getMethodName != methodName) stackTraceList.takeWhile(st => st.getFileName != fileName || st.getMethodName != methodName).length else includeDepth depth + adjustment } // Clears the text field or area, then presses the passed keys /** * Clears the current active <code>TextField</code> or <code>TextArea</code>, and presses the passed keys. * Throws <code>TestFailedException</code> if current active is not <code>TextField</code> or <code>TextArea</code>. * * @param value keys to press in current active <code>TextField</code> or <code>TextArea</code> */ def enter(value: String)(implicit driver: WebDriver) { val ae = switch to activeElement ae match { case tf: TextField => tf.value = value case ta: TextArea => ta.value = value case pf: PasswordField => pf.value = value case pf: EmailField => pf.value = value case pf: SearchField => pf.value = value case pf: TelField => pf.value = value case pf: UrlField => pf.value = value case _ => throw new TestFailedException( sde => Some("Currently selected element is neither a text field, text area, password field, email field, search field, tel field or url field"), None, getStackDepthFun("WebBrowser.scala", "switch", 1) ) } } /** * Press the passed keys to current active element. * * @param value keys to press in current active element */ def pressKeys(value: String)(implicit driver: WebDriver) { val ae: WebElement = driver.switchTo.activeElement ae.sendKeys(value) } } /** * Companion object that facilitates the importing of <code>WebBrowser</code> members as * an alternative to mixing it in. One use case is to import <code>WebBrowser</code> members so you can use * them in the Scala interpreter. */ object WebBrowser extends WebBrowser /** * Trait declaring a <code>webDriver</code> field that enables tests to be abstracted across different kinds of <code>WebDriver</code>s. * * <p> * This trait enables you to place tests that you want to run in multiple browsers in a trait with a self type of * <code>WebBrowser with Driver</code>, like this: * </p> * * <pre class="stHighlight"> * trait MyBrowserTests { * this: WebBrowser with Driver =&gt; * // Your browser tests * } * </pre> * * Then you can create concrete subclasses for each actual browser you want to run those tests in: * * <pre class="stHighlight"> * class MyBrowserTestsWithChrome extends MyBrowserTests with Chrome * class MyBrowserTestsWithSafari extends MyBrowserTests with Safari * class MyBrowserTestsWithInternetExplorer extends MyBrowserTests with InternetExplorer * class MyBrowserTestsWithFirefox extends MyBrowserTests with Firefox * </pre> */ trait Driver { this: WebBrowser => /** * An implicit <code>WebDriver</code>. * * <p> * This abstract field is implemented by subtraits <code>HtmlUnit</code>, <code>FireFox</code>, <code>Safari</code>, <code>Chrome</code>, * and <code>InternetExplorer</code>. * </p> */ implicit val webDriver: WebDriver } /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for HTMLUnit (an <code>org.openqa.selenium.htmlunit.HtmlUnitDriver</code>), with JavaScript * enabled by default. * * <p> * Note: You can disable JavaScript with: * </p> * * <pre> * webDriver.setJavascriptEnabled(false) * </pre> */ trait HtmlUnit extends WebBrowser with Driver with ScreenshotCapturer { /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for HTMLUnit (an <code>org.openqa.selenium.htmlunit.HtmlUnitDriver</code>), with JavaScript * enabled by default. * * <p> * Note: You can disable JavaScript with: * </p> * * <pre> * webDriver.setJavascriptEnabled(false) * </pre> */ implicit val webDriver = new HtmlUnitDriver() webDriver.setJavascriptEnabled(true) /** * Captures a screenshot and saves it as a file in the specified directory. */ def captureScreenshot(directory: String) { capture to directory } } /** * Companion object that facilitates the importing of <code>HtmlUnit</code> members as * an alternative to mixing it in. One use case is to import <code>HtmlUnit</code> members so you can use * them in the Scala interpreter. */ object HtmlUnit extends HtmlUnit /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Firefox (an <code>org.openqa.selenium.firefox.FirefoxDriver</code>). * * <p> * The <code>FirefoxDriver</code> uses the <code>FirefoxProfile</code> defined as <code>firefoxProfile</code>. By default this is just a <code>new FirefoxProfile</code>. * You can mutate this object to modify the profile, or override <code>firefoxProfile</code>. * </p> */ trait Firefox extends WebBrowser with Driver with ScreenshotCapturer { /** * The <code>FirefoxProfile</code> passed to the constructor of the <code>FirefoxDriver</code> returned by <code>webDriver</code>. * * <p> * The <code>FirefoxDriver</code> uses the <code>FirefoxProfile</code> defined as <code>firefoxProfile</code>. By default this is just a <code>new FirefoxProfile</code>. * You can mutate this object to modify the profile, or override <code>firefoxProfile</code>. * </p> */ val firefoxProfile = new FirefoxProfile() /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Firefox (an <code>org.openqa.selenium.firefox.FirefoxDriver</code>), with a default * Firefox profile. * * <p> * The <code>FirefoxDriver</code> uses the <code>FirefoxProfile</code> defined as <code>firefoxProfile</code>. By default this is just a <code>new FirefoxProfile</code>. * You can mutate this object to modify the profile, or override <code>firefoxProfile</code>. * </p> */ implicit val webDriver = new FirefoxDriver(firefoxProfile) /** * Captures a screenshot and saves it as a file in the specified directory. */ def captureScreenshot(directory: String) { capture to directory } } /** * Companion object that facilitates the importing of <code>Firefox</code> members as * an alternative to mixing it in. One use case is to import <code>Firefox</code> members so you can use * them in the Scala interpreter. */ object Firefox extends Firefox /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Safari (an <code>org.openqa.selenium.safari.SafariDriver</code>). */ trait Safari extends WebBrowser with Driver with ScreenshotCapturer { /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Safari (an <code>org.openqa.selenium.safari.SafariDriver</code>). */ implicit val webDriver = new SafariDriver() /** * Captures a screenshot and saves it as a file in the specified directory. */ def captureScreenshot(directory: String) { capture to directory } } /** * Companion object that facilitates the importing of <code>Safari</code> members as * an alternative to mixing it in. One use case is to import <code>Safari</code> members so you can use * them in the Scala interpreter. */ object Safari extends Safari /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Chrome (an <code>org.openqa.selenium.chrome.ChromeDriver</code>). */ trait Chrome extends WebBrowser with Driver with ScreenshotCapturer { /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Chrome (an <code>org.openqa.selenium.chrome.ChromeDriver</code>). */ implicit val webDriver = new ChromeDriver() /** * Captures a screenshot and saves it as a file in the specified directory. */ def captureScreenshot(directory: String) { capture to directory } } /** * Companion object that facilitates the importing of <code>Chrome</code> members as * an alternative to mixing it in. One use case is to import <code>Chrome</code> members so you can use * them in the Scala interpreter. */ object Chrome extends Chrome /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Internet Explorer (an <code>org.openqa.selenium.ie.InternetExplorerDriver</code>). */ trait InternetExplorer extends WebBrowser with Driver with ScreenshotCapturer { /** * <code>WebBrowser</code> subtrait that defines an implicit <code>WebDriver</code> for Internet Explorer (an <code>org.openqa.selenium.ie.InternetExplorerDriver</code>). */ implicit val webDriver = new InternetExplorerDriver() /** * Captures a screenshot and saves it as a file in the specified directory. */ def captureScreenshot(directory: String) { capture to directory } } /** * Companion object that facilitates the importing of <code>InternetExplorer</code> members as * an alternative to mixing it in. One use case is to import <code>InternetExplorer</code> members so you can use * them in the Scala interpreter. */ object InternetExplorer extends InternetExplorer /* * <p> * If you mix in <a href="../ScreenshotOnFailure.html"><code>ScreenshotOnFailure</code></a>, ScalaTest will capture a screenshot and store it to either the system temp directory * or a directory you choose, and send the filename to the report, associated with the failed test. The <code>ScreenshotOnFailure</code> trait requires that it be * mixed into a <a href="../ScreenshotCapturer.html"><code>ScreenshotCapturer</code></a>, which trait <code>WebBrowser</code> does not extend. To satisfy this * requirement, you can extend one of <code>WebBrowser</code>'s subtraits, such as: * </p> * * <pre class="stHighlight"> * class WebAppSpec extends Firefox with ScreenshotOnFailure { * // ... * } * </pre> * */
SRGOM/scalatest
scalatest/src/main/scala/org/scalatest/selenium/WebBrowser.scala
Scala
apache-2.0
177,684
package hevs.especial.simulation import hevs.especial.dsl.components.core.{Constant, Mux2, TickToggle} import hevs.especial.dsl.components.target.stm32stk.Stm32stkIO import hevs.especial.dsl.components.{bool, uint8} import hevs.especial.generator.STM32TestSuite /** * Test case for the QEMU simulation. * Use [[TickToggle]] generator and a [[Mux2]] to produce output values to two LEDs. * * This program can be simulated in QEMU (see [[Sch6Simulation]] test case). * After 6 loop ticks, output values are the following : * {{ * Pin 'C#03' has 06 values: 1-0-1-0-1-0 * Pin 'C#04' has 06 values: 1-1-1-1-1-1 * }} * * @version 1.0 * @author Christopher Metrailler (mei@hevs.ch) */ class Sch6SimCode extends STM32TestSuite { def isQemuLoggerEnabled = true import hevs.especial.dsl.components.CType.Implicits._ def runDslCode(): Unit = { // Inputs val cst1 = Constant[bool](true).out val cst2 = Constant[bool](false).out val cst3 = Constant(uint8(0)).out val gen1 = TickToggle(cst2).out val gen2 = TickToggle(cst3).out // Logic val mux1 = Mux2[bool]() // Output val led1 = Stm32stkIO.led1 val led2 = Stm32stkIO.led2 // Connecting stuff cst1 --> mux1.in1 gen1 --> mux1.in2 gen2 --> mux1.sel gen1 --> led1.in mux1.out --> led2.in } runDotGeneratorTest() runCodeCheckerTest(hasWarnings = false) runCodeOptimizer() runDotGeneratorTest(optimizedVersion = true) runCodeGenTest() }
hevs-isi/especial-frontend
src/test/scala/hevs/especial/simulation/Sch6SimCode.scala
Scala
mit
1,483
package org.coursera.naptime.ari.graphql.schema import com.linkedin.data.DataMap import com.linkedin.data.schema.NamedDataSchema import com.linkedin.data.schema.RecordDataSchema.{Field => RecordDataSchemaField} import com.linkedin.data.schema.UnionDataSchema import org.coursera.naptime.ari.graphql.SangriaGraphQlContext import sangria.schema.Field import sangria.schema.ObjectType import sangria.schema.Schema import sangria.schema.UnionType import scala.collection.JavaConverters._ object NaptimeUnionField { val TYPED_DEFINITION_KEY = "typedDefinition" val NAMESPACE_KEY = "namespace" private[schema] def build( schemaMetadata: SchemaMetadata, unionDataSchema: UnionDataSchema, fieldName: String, namespace: Option[String], resourceName: String): Field[SangriaGraphQlContext, DataMap] = { Field.apply[SangriaGraphQlContext, DataMap, Any, Any]( name = fieldName, fieldType = getType(schemaMetadata, unionDataSchema, fieldName, namespace, resourceName), resolve = context => { if (unionDataSchema.getProperties.containsKey(TYPED_DEFINITION_KEY)) { val definition = context.value.getDataMap(fieldName).getDataMap("definition") val typeName = context.value.getDataMap(fieldName).getString("typeName") new DataMap(Map(typeName -> definition).asJava) } else { context.value.getDataMap(fieldName) } }) } private[schema] def getType( schemaMetadata: SchemaMetadata, unionDataSchema: UnionDataSchema, fieldName: String, namespace: Option[String], resourceName: String): UnionType[SangriaGraphQlContext] = { val objects = unionDataSchema.getTypes.asScala.map { subType => val typedDefinitions = Option(unionDataSchema.getProperties.get(TYPED_DEFINITION_KEY)).collect { case definitions: java.util.Map[String @unchecked, String @unchecked] => definitions.asScala }.getOrElse(Map[String, String]()) val unionMemberKey = subType match { case _ if typedDefinitions.contains(subType.getUnionMemberKey) => typedDefinitions(subType.getUnionMemberKey) case namedType: NamedDataSchema if typedDefinitions.contains(namedType.getName) && unionDataSchema.getProperties.get(NAMESPACE_KEY) == namedType.getNamespace => typedDefinitions(namedType.getName) case _ => subType.getUnionMemberKey } val unionMemberFieldName = FieldBuilder.formatName(unionMemberKey) val subTypeField = FieldBuilder.buildField( schemaMetadata, new RecordDataSchemaField(subType), namespace, Some(unionMemberKey), resourceName = resourceName) val field = Field.apply[SangriaGraphQlContext, DataMap, Any, Any]( unionMemberFieldName, subTypeField.fieldType, resolve = subTypeField.resolve) ObjectType[SangriaGraphQlContext, DataMap]( name = FieldBuilder.formatName(s"$resourceName/${unionMemberKey}Member"), fields = List(field)) }.toList val unionName = buildFullyQualifiedName(resourceName, fieldName) new UnionType(unionName, None, objects) { // write a custom type mapper to use field names to determine the union member type override def typeOf[Ctx](value: Any, schema: Schema[Ctx, _]): Option[ObjectType[Ctx, _]] = { val typedValue = value.asInstanceOf[DataMap] objects.find { obj => val formattedMemberNames = typedValue.keySet.asScala .flatMap(key => Option(key)) .map(FieldBuilder.formatName) obj.fieldsByName.keySet.intersect(formattedMemberNames).nonEmpty }.map(_.asInstanceOf[ObjectType[Ctx, DataMap]]) } } } def buildFullyQualifiedName(namespace: String, fieldName: String): String = { FieldBuilder.formatName(s"$namespace.$fieldName") } }
vkuo-coursera/naptime
naptime-graphql/src/main/scala/org/coursera/naptime/ari/graphql/schema/NaptimeUnionField.scala
Scala
apache-2.0
3,900
package dao.postgres.marshalling import java.sql.{Connection, PreparedStatement, ResultSet} import java.util.UUID import dao.postgres.common.{ProcessTriggerRequestTable, TaskTriggerRequestTable} import model.ProcessTriggerRequest import util.JdbcUtil._ object ProcessTriggerRequestMarshaller { def marshal(request: ProcessTriggerRequest, stmt: PreparedStatement, columns: Seq[String], startIndex: Int = 1)(implicit conn: Connection) = { import ProcessTriggerRequestTable._ var index = startIndex columns.foreach { col => col match { case COL_REQUEST_ID => stmt.setObject(index, request.requestId) case COL_PROCESS_DEF_NAME => stmt.setString(index, request.processDefinitionName) case COL_REQUESTED_AT => stmt.setTimestamp(index, request.requestedAt) case COL_STARTED_PROCESS_ID => stmt.setObject(index, request.startedProcessId.orNull) case COL_TASK_FILTER => stmt.setArray(index, request.taskFilter.map(makeStringArray).orNull) } index += 1 } } def unmarshal(rs: ResultSet): ProcessTriggerRequest = { import ProcessTriggerRequestTable._ ProcessTriggerRequest( requestId = rs.getObject(COL_REQUEST_ID).asInstanceOf[UUID], processDefinitionName = rs.getString(COL_PROCESS_DEF_NAME), requestedAt = javaDate(rs.getTimestamp(COL_REQUESTED_AT)), startedProcessId = Option(rs.getObject(COL_STARTED_PROCESS_ID)).map(_.asInstanceOf[UUID]), taskFilter = getStringArray(rs, COL_TASK_FILTER) ) } }
gilt/sundial
app/dao/postgres/marshalling/ProcessTriggerRequestMarshaller.scala
Scala
mit
1,597
/** * Copyright 2014 Gianluca Amato <gamato@unich.it> * * This filteq is part of JANDOM: JVM-based Analyzer for Numerical DOMains * JANDOM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JANDOM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of a * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JANDOM. If not, see <http://www.gnu.org/licenses/>. */ package it.unich.jandom.objectmodels import org.scalatest._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.prop.TableFor1 /** * This is a trait for test suites of object models. * @author Gianluca Amato <gamato@unich.it> * @todo Add a generator for paths */ trait ObjectModelSuite extends FunSpec with TableDrivenPropertyChecks { /** * The object model we want to test */ val om: ObjectModel import om._ /** * All types we want to check */ val someTypes: TableFor1[Type] describe("The declared fields of a type") { they("are disjoint for different types") { for (t1 <- someTypes; t2 <- someTypes; if t1 != t2) assert((declaredFields(t1) intersect declaredFields(t2)).isEmpty) } } describe("The typeOf method") { it("returns a type for each field") { for (t <- someTypes) { val fields = declaredFields(t) // I want to check absence of exception, I do not know if there is a standard method fields map { typeOf(_) } } } } describe("The subtype relation") { it("is reflexive") { for (t <- someTypes) assert(lteq(t, t)) } it("is anti-symmetric") { for (t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2) && lteq(t2, t1)) assert(t1 === t2) } it("is transitive") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes; if lteq(t1, t2) && lteq(t2, t3)) assert(lteq(t2, t3)) } } describe("The parents of a type t") { they("are super-types of t") { for (t1 <- someTypes; t2 <- parents(t1)) assert(lteq(t1, t2)) } they("do not contain t itself") { for (t <- someTypes) assert(!(parents(t) contains t)) } } describe("The children of a type t") { they("are sub-types of t") { for (t1 <- someTypes; t2 <- children(t1)) assert(lteq(t2, t1)) } they("do not contain t itself") { for (t <- someTypes) assert(!(children(t) contains t)) } } describe("The ancestors of a type t") { they("are super-types of t") { for (t1 <- someTypes; t2 <- ancestors(t1)) assert(lteq(t1, t2)) } they("do contain t itself") { for (t <- someTypes) assert(ancestors(t) contains t) } they("are a superset of the parents of t") { for (t <- someTypes) assert(parents(t) subsetOf ancestors(t)) } they("are anti-monotonic w.r.t. sub-type relationship") { for (t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2)) assert(ancestors(t2) subsetOf ancestors(t1)) } } describe("The descendants of a type t") { they("are sub-types of t") { for (t1 <- someTypes; t2 <- descendants(t1)) assert(lteq(t2, t1)) } they("do contain t itself") { for (t <- someTypes) assert(descendants(t) contains t) } they("are a superset of the children of t") { for (t <- someTypes) assert(children(t) subsetOf descendants(t)) } they("are monotonic w.r.t. sub-type relationship") { for (t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2)) assert(descendants(t1) subsetOf descendants(t2), s"descendants of ${t1} is not a subset of descendants of ${t2}") } } describe("The fields of a type") { they("are monotonic w.r.t. subtype relationship") { for (t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2)) assert(fields(t2) subsetOf fields(t1)) } they("contain the decleated fields of the same type") { for (t <- someTypes) assert(declaredFields(t) subsetOf fields(t)) } } describe("The concretizability of a type") { it("is upward closed") { for { t1 <- someTypes; t2 <- someTypes; if isConcretizable(t1) && lteq(t1, t2) } assert(isConcretizable(t2), s"${t1} may be instantiated but ${t2} cannot") } it("is always true for concrete types") { for (t <- someTypes; if isConcrete(t)) assert(isConcretizable(t)) } } describe("The needed fields of a type") { they("are empty on non concretizable types") { for { t <- someTypes; if !isConcretizable(t) } { assert(neededFields(t).isEmpty) } } they("contain the fields of the type if the type is concretizable") { for { t <- someTypes; if isConcretizable(t) } { assert(fields(t) subsetOf neededFields(t)) } } they("are anti-monotone w.r.t. subtype relationship for concretizable types") { for { t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2) && isConcretizable(t1) } { val fields1 = neededFields(t1) val fields2 = neededFields(t2) assert(fields2 subsetOf fields1, s"${fields2} is not a subset of ${fields1}") } } } describe("The possible fields of a type") { they("are empty on non concretizable types") { for { t <- someTypes; if !isConcretizable(t) } { assert(possibleFields(t).isEmpty) } } they("are a superset of the needed fields") { for { t <- someTypes } { assert(neededFields(t) subsetOf possibleFields(t)) } } they("are monotone w.r.t. subtype relationship") { for { t1 <- someTypes; t2 <- someTypes; if lteq(t1, t2) } { val fields1 = possibleFields(t1) val fields2 = possibleFields(t2) assert(fields1 subsetOf fields2, s"${fields1} is not a subset of ${fields2}") } } } describe("Type reachability") { it("is reflexive for types which may share with other types") { for { t1 <- someTypes; t2 <- someTypes; if mayShare(t1, t2) } assert(reachablesFrom(t1) contains t1) } it("is transitive") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { if (isReachable(t1, t2) && isReachable(t2, t3)) { assert(isReachable(t1, t3), s"${t1} may reach ${t2} which may reach ${t3}, but ${t1} cannot reach ${t3}") } } } it("is downward closed on the target") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { if (isReachable(t1, t2) && lteq(t3, t2)) { assert(isReachable(t1, t3)) } } } it("is upward closed on the source") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { if (isReachable(t1, t2) && lteq(t1, t3)) { assert(isReachable(t3, t2)) } } } } describe("The upper crown operator") { it("returns empty set for empty sequences") { assert(upperCrown(Seq()).isEmpty) } it("returns the only element in length one sequence") { for (t <- someTypes) assert(upperCrown(Seq(t)) == Set(t)) } it("is commutative") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { val base = upperCrown(Seq(t1, t2, t3)) assert(upperCrown(Seq(t1, t3, t2)) === base) assert(upperCrown(Seq(t2, t1, t3)) === base) assert(upperCrown(Seq(t2, t3, t1)) === base) assert(upperCrown(Seq(t3, t1, t2)) === base) assert(upperCrown(Seq(t3, t2, t1)) === base) } } it("returns a set of incomparable elements") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { val crown = upperCrown(Seq(t1, t2, t3)) for (ta <- crown; tb <- crown; if ta != tb) assert(!lteq(ta, tb) && !lteq(tb, ta), s"ta = ${ta} and tb = ${tb}") } } it("is equal to the concreteApprox when the two arguments are equal") { for (t <- someTypes) { assert(concreteApprox(t) === concreteApprox(t, t), s"for t = ${t}") } } } describe("The binary concreteApprox operator") { it("is idempotent on concrete type, reductive on concretizable types, empty on non concretizables") { for (t <- someTypes) { val glb = concreteApprox(t, t) if (isConcrete(t)) { assert(glb.isDefined) assert(glb.get === t) } else if (isConcretizable(t)) { assert(glb.isDefined) assert(lteq(glb.get, t)) } else { assert(glb.isEmpty) } } } it("is bigger than all other concrete lower bounds") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes; if lteq(t3, t1) && lteq(t3, t2) && isConcrete(t3)) { val glb = concreteApprox(t1, t2) assert(glb.isDefined) assert(lteq(t3, glb.get)) } } it("returns a concretizable type") { for (t1 <- someTypes; t2 <- someTypes; glb = concreteApprox(t1, t2); if glb.isDefined) { assert(isConcretizable(glb.get)) } } } describe("The elementType method") { it("returns a type for arrays") { for (t <- someTypes; if (isArray(t))) assert(elementType(t).isDefined) } } describe("The pathExists method") { it("returns true for empty paths") { for (t <- someTypes) assert(pathExists(t)) } it("returns true for qualified identifiers") { for (t <- someTypes; f <- fields(t)) assert(pathExists(t,f)) } it("returns false for non-valid qualified identifiers") { for (t <- someTypes; t2 <- someTypes; if !lteq(t,t2); f <- declaredFields(t2)) assert(!pathExists(t,f)) } } describe("The concreteApprox of a sequence of types") { it("is undefined for empty sequences") { assert(concreteApprox(Seq()).isEmpty) } it("is equivalent to binary concreteApprox with two argument equals for length one sequences") { for (t <- someTypes) { assert(concreteApprox(Seq(t)) === concreteApprox(t, t)) } } it("is equal to the binary concreteApprox for length two sequences") { for (t1 <- someTypes; t2 <- someTypes) { assert(concreteApprox(Seq(t1, t2)) === concreteApprox(t1, t2)) } } it("may be obtained by iterating the binary glb operator") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes) { val ts = Seq(t1, t2, t3) assert(concreteApprox(ts) === (concreteApprox(t2, t3) flatMap { concreteApprox(t1, _) }), s"for glb of ${t1}, ${t2} and ${t3}") } } } describe("Possible aliasing information") { it("is reflexive on non-primitive concretizable types") { for (t <- someTypes; if !isPrimitive(t) && isConcretizable(t)) assert(mayBeAliases(t, t)) } it("is symmetric") { for (t1 <- someTypes; t2 <- someTypes) assert(mayBeAliases(t1, t2) === mayBeAliases(t2, t1)) } it("corresponds to having a defined concreteApprox and being non-primitive") { for (t1 <- someTypes; t2 <- someTypes) { val aliasable = concreteApprox(t1, t2).isDefined && !isPrimitive(t1) && !isPrimitive(t2) assert(mayBeAliases(t1, t2) === aliasable) } } it("is upward closed") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes; if mayBeAliases(t1, t2)) { if (lteq(t2, t3)) assert(mayBeAliases(t1, t3), s"${t1} may be alias with ${t2} and ${t1} <= ${t3}") if (lteq(t1, t3)) assert(mayBeAliases(t2, t3), s"${t1} may be alias with ${t2} and ${t2} <= ${t3}") } } } describe("Possible sharing information") { it("is reflexive for non-primitive concretizable types") { for { t <- someTypes; if !isPrimitive(t) && isConcretizable(t) } assert(mayShare(t, t)) } it("is reflexive for types which shares with other types") { for (t1 <- someTypes; t2 <- someTypes; if mayShare(t1, t2)) { assert(mayShare(t1, t1)) } } it("is symmetric") { for { t1 <- someTypes; t2 <- someTypes } assert(mayShare(t2, t1) === mayShare(t2, t1)) } it("is upward closed") { for (t1 <- someTypes; t2 <- someTypes; t3 <- someTypes; if mayShare(t1, t2)) { if (lteq(t2, t3)) assert(mayShare(t1, t3), s"${t1} share with ${t2} and ${t1} <= ${t3}") if (lteq(t1, t3)) assert(mayShare(t2, t3), s"${t1} share with ${t2} and ${t2} <= ${t3}") } } } }
amato-gianluca/Jandom
core/src/test/scala/it/unich/jandom/objectmodels/ObjectModelSuite.scala
Scala
lgpl-3.0
12,724
package org.openmole.core.workflow.test import org.openmole.core.context.Context import org.openmole.core.workflow.builder.DefinitionScope import org.openmole.core.workflow.task.ClosureTask object TestTask { def apply(f: Context ⇒ Context)(implicit name: sourcecode.Name, definitionScope: DefinitionScope) = ClosureTask("TestTask")((ctx, _, _) ⇒ f(ctx)) }
openmole/openmole
openmole/core/org.openmole.core.workflow/src/main/scala/org/openmole/core/workflow/test/TestTask.scala
Scala
agpl-3.0
370
package com.scout24.pipedsl.model class S3DataNode(id : String, path : FileOrDirectoryPath, sched : Schedule) extends DataNode(id, "S3DataNode") { path match { case FilePath(path) => addValueField("filePath", path) case DirectoryPath(path) => addValueField("directoryPath", path) case ManifestFilePath(path) => addValueField("manifestFilePath", path) } if (sched != null) { addReferenceField("schedule", sched) } } abstract class FileOrDirectoryPath case class FilePath(path : String) extends FileOrDirectoryPath case class DirectoryPath(path : String) extends FileOrDirectoryPath case class ManifestFilePath(path : String) extends FileOrDirectoryPath
matey-jack/pipe-dsl
src/main/scala/com/scout24/pipedsl/model/S3DataNode.scala
Scala
gpl-2.0
684
package chandu0101.scalajs.react.components package materialui import chandu0101.macros.tojs.JSMacro import japgolly.scalajs.react._ import japgolly.scalajs.react.raw.React import japgolly.scalajs.react.vdom.{VdomElement, VdomNode} import scala.scalajs.js import scala.scalajs.js.`|` /** * This file is generated - submit issues instead of PR against it */ case class MuiTab[T](key: js.UndefOr[String] = js.undefined, ref: js.UndefOr[String] = js.undefined, /* Override the inline-styles of the button element. */ buttonStyle: js.UndefOr[CssProperties] = js.undefined, /* The css class name of the root element. */ className: js.UndefOr[String] = js.undefined, /* Sets the icon of the tab, you can pass `FontIcon` or `SvgIcon` elements. */ icon: js.UndefOr[VdomNode] = js.undefined, index: js.UndefOr[js.Any] = js.undefined, /* Sets the text value of the tab item to the string specified. */ label: js.UndefOr[VdomNode] = js.undefined, /* Fired when the active tab changes by touch or tap. Use this event to specify any functionality when an active tab changes. For example - we are using this to route to home when the third tab becomes active. This function will always recieve the active tab as it\\'s first argument. */ onActive: js.UndefOr[VdomElement => Callback] = js.undefined, /* This property is overriden by the Tabs component. */ onTouchTap: js.UndefOr[TouchTapEvent => Callback] = js.undefined, /* Defines if the current tab is selected or not. The Tabs component is responsible for setting this property. */ selected: js.UndefOr[Boolean] = js.undefined, /* Override the inline-styles of the root element. */ style: js.UndefOr[CssProperties] = js.undefined, /* If value prop passed to Tabs component, this value prop is also required. It assigns a value to the tab so that it can be selected by the Tabs. */ value: js.UndefOr[T] = js.undefined, /* This property is overriden by the Tabs component. */ width: js.UndefOr[String] = js.undefined, /* (Passed on to EnhancedButton) */ centerRipple: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ containerElement: js.UndefOr[String | VdomElement] = js.undefined, /* (Passed on to EnhancedButton) */ disableFocusRipple: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ disableKeyboardFocus: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ disableTouchRipple: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ disabled: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ focusRippleColor: js.UndefOr[MuiColor] = js.undefined, /* (Passed on to EnhancedButton) */ focusRippleOpacity: js.UndefOr[Double] = js.undefined, /* (Passed on to EnhancedButton) */ href: js.UndefOr[String] = js.undefined, /* (Passed on to EnhancedButton) */ keyboardFocused: js.UndefOr[Boolean] = js.undefined, /* (Passed on to EnhancedButton) */ onBlur: js.UndefOr[ReactFocusEvent => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ onClick: js.UndefOr[ReactEvent => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ onFocus: js.UndefOr[ReactFocusEvent => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ onKeyDown: js.UndefOr[ReactKeyboardEvent => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ onKeyUp: js.UndefOr[ReactKeyboardEvent => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ onKeyboardFocus: js.UndefOr[(ReactFocusEvent, Boolean) => Callback] = js.undefined, /* (Passed on to EnhancedButton) */ tabIndex: js.UndefOr[Double] = js.undefined, /* (Passed on to EnhancedButton) */ touchRippleColor: js.UndefOr[MuiColor] = js.undefined, /* (Passed on to EnhancedButton) */ touchRippleOpacity: js.UndefOr[Double] = js.undefined, /* (Passed on to EnhancedButton) */ `type`: js.UndefOr[String] = js.undefined) { def apply(children: VdomNode*) = { implicit def evT(t: T): js.Any = t.asInstanceOf[js.Any] val props = JSMacro[MuiTab[T]](this) val component = JsComponent[js.Object, Children.Varargs, Null](Mui.Tab) component(props)(children: _*) } }
rleibman/scalajs-react-components
core/src/main/scala/chandu0101/scalajs/react/components/materialui/MuiTab.scala
Scala
apache-2.0
5,474
package com.github.gigurra.glasciia import scala.concurrent.ExecutionContext /** * Created by johan on 2017-01-04. */ object SameThreadExecutionContext extends ExecutionContext { override def execute(runnable: Runnable): Unit = runnable.run() override def reportFailure(cause: Throwable): Unit = throw cause }
GiGurra/glasciia
glasciia-core/src/main/scala/com/github/gigurra/glasciia/SameThreadExecutionContext.scala
Scala
mit
320
package net.mentalarray.doozie.PigSupport import java.util.UUID import scala.concurrent.Promise /** * Created by kdivincenzo on 2/18/15. */ protected[PigSupport] class PigWorkItem(task: PigTask) { // The work ID private val workId = UUID.randomUUID def id : UUID = workId // The PigTask def pigTask = task // The promise for the work item private val workPromise = Promise[Boolean] // Future for the work promise def workFuture = workPromise.future // Handle work completed results def handleWorkCompletedResult(result: Boolean) = workPromise success result def handleWorkCompletedResult(ex: Exception) = workPromise failure ex }
antagonist112358/tomahawk
workflow-engine/src/net/mentalarray/doozie/PigSupport/PigWorkItem.scala
Scala
apache-2.0
663
//https://www.hackerrank.com/challenges/stocks-prediction object StocksPrediction extends App { case class Query(d: Int, m: Int) import scala.collection.mutable.{HashMap ⇒ MMap} val cache = MMap[Query, Int]() // let's cache prev results // reading inputs like this is faster than following io.Source.stdin.getLines approach val N = io.StdIn.readInt() val A = io.StdIn.readLine().split(' ').toArray.map(_.toInt) val Q = io.StdIn.readInt() def search(d: Int, m: Int) = { val low = A(d) val high = low + m def offRange(a: Int) = (a < low || a > high) // let's play with indexes def searchLeft(idx: Int): Int = { if (idx < 0 || offRange(A(idx))) d - (idx + 1) else searchLeft(idx - 1) } def searchRight(idx: Int): Int = { if (idx >= N || offRange(A(idx))) idx - d else searchRight(idx + 1) } searchLeft(d - 1) + searchRight(d + 1) } for (_ <- 1 to Q) { val Array(d, m) = io.StdIn.readLine().split(' ').toArray.map(_.toInt) println(cache getOrElseUpdate (Query(d, m), search(d, m))) } }
flopezlasanta/hackerrank
src/functional_programming/functional_structures/StocksPrediction.scala
Scala
mit
1,066
/* * Copyright (C) 2010-2014 GRNET S.A. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gr.grnet.cdmi.service import java.net.URL import java.nio.charset.StandardCharsets import java.util.Locale import com.fasterxml.jackson.databind.node.JsonNodeType import com.google.common.cache.{CacheBuilder, CacheLoader} import com.twitter.app.{App, GlobalFlag} import com.twitter.finagle.httpx.{RequestBuilder, Status} import com.twitter.io.Buf import com.twitter.logging.{Level, Logging} import com.twitter.util._ import gr.grnet.cdmi.metadata.StorageSystemMetadata import gr.grnet.cdmi.model.{ContainerModel, Model, ObjectModel} import gr.grnet.common.http.{StdHeader, StdMediaType, TResult} import gr.grnet.common.io.Base64 import gr.grnet.common.json.Json import gr.grnet.common.text.{ParentPath, RemovePrefix} import gr.grnet.pithosj.api.PithosApi import gr.grnet.pithosj.core.ServiceInfo import gr.grnet.pithosj.core.command.{CheckExistsObjectResultData, GetObject2ResultData} import gr.grnet.pithosj.impl.finagle.{FinagleClientFactory, PithosClientFactory} import scala.collection.immutable.Seq object pithosTimeout extends GlobalFlag[Long]( 1000L * 60L * 3L /* 3 min*/, "millis to wait for Pithos response") object pithosServerURL extends GlobalFlag[String]( "https://pithos.okeanos.grnet.gr", "Pithos server URL") object pithosRootPath extends GlobalFlag[String]( "/object-store/v1", "Pithos service root path prefix. All Pithos requests have this prefix") object pithosUUID extends GlobalFlag[String]( "", "Pithos (Astakos) UUID. Usually set for debugging") object pithosToken extends GlobalFlag[String]( "", "Pithos (Astakos) Token. Set this only for debugging") object authURL extends GlobalFlag[String]( "https://okeanos-occi2.hellasgrid.gr:5000/main", "auth proxy") object authRedirect extends GlobalFlag[Boolean]( true, "Redirect to 'authURL' if token is not present (in an attempt to get one)") object tokensURL extends GlobalFlag[String]( "https://accounts.okeanos.grnet.gr/identity/v2.0/tokens", "Used to obtain UUID from token") /** * A Pithos-based implementation for the CDMI service * * @author Christos KK Loverdos <loverdos@gmail.com> */ object StdCdmiPithosServer extends CdmiRestService with App with Logging with CdmiRestServiceTypes with CdmiRestServiceHandlers with CdmiRestServiceMethods with CdmiRestServiceResponse { override def defaultLogLevel: Level = Level.DEBUG final val X_Pithos_Server_URL = "X-Pithos-Server-URL" final val X_Pithos_Root_Path = "X-Pithos-Root-Path" final val X_Pithos_UUID = "X-Pithos-UUID" final val X_Pithos_Token = "X-Pithos-Token" final val X_Auth_Token = "X-Auth-Token" final val wwwAuthenticateValue = s"Keystone uri='${authURL()}'" val pithosApiCache = CacheBuilder. newBuilder(). maximumSize(50). build[ServiceInfo, PithosApi]( new CacheLoader[ServiceInfo, PithosApi] { def load(serviceInfo: ServiceInfo): PithosApi = PithosClientFactory.newClient(serviceInfo) } ) def pithos(serviceInfo: ServiceInfo): PithosApi = pithosApiCache.get(serviceInfo) def getPithosServerURL(request: Request): String = { val headers = request.headerMap if(!headers.contains(X_Pithos_Server_URL)) { if(!pithosServerURL().isEmpty) { headers.add(X_Pithos_Server_URL, pithosServerURL()) } } headers.get(X_Pithos_Server_URL).orNull } def getPithosRootPath(request: Request): String = { val headers = request.headerMap if(!headers.contains(X_Pithos_Root_Path)) { if(!pithosRootPath().isEmpty) { headers.add(X_Pithos_Root_Path, pithosRootPath()) } } headers.get(X_Pithos_Root_Path).orNull } def getPithosUUID(request: Request): String = { val headers = request.headerMap if(!headers.contains(X_Pithos_UUID)) { if(!pithosUUID().isEmpty) { headers.add(X_Pithos_UUID, pithosUUID()) } } headers.get(X_Pithos_UUID).orNull } def getPithosToken(request: Request): String = { val headers = request.headerMap if(!headers.contains(X_Pithos_Token)) { if(headers.contains(X_Auth_Token)) { headers.add(X_Pithos_Token, headers.get(X_Auth_Token).orNull) } } headers.get(X_Pithos_Token).orNull } def checkPithosToken(request: Request): Boolean = getPithosToken(request) ne null def getPithosServiceInfo(request: Request): ServiceInfo = { val headers = request.headerMap val serverURL = new URL(headers.get(X_Pithos_Server_URL).orNull) val rootPath = headers.get(X_Pithos_Root_Path).orNull val uuid = headers.get(X_Pithos_UUID).orNull val token = headers.get(X_Pithos_Token).orNull ServiceInfo( serverURL = serverURL, rootPath = rootPath, uuid = uuid, token = token ) } val authFilter = new Filter { def authenticateResponse(request: Request): Response = { val response = request.response response.status = Status.Unauthorized val rh = response.headerMap rh.add(HeaderNames.Content_Type, MediaTypes.Text_Html) rh.add(HeaderNames.WWW_Authenticate, wwwAuthenticateValue) rh.add(HeaderNames.Content_Length, "0") response } override def apply(request: Request, service: Service): Future[Response] = { if(isCdmiCapabilitiesUri(request.uri)) { return service(request) } // If we do not have the X-Auth-Token header present, then we need to send the user for authentication getPithosToken(request) match { case null if authRedirect() ⇒ log.warning(s"Unauthenticated ${request.method} ${request.uri}") val response = authenticateResponse(request) logEndRequest(request, response) response.future case _ ⇒ service(request) } } } final val postTokensJsonFmt = """{ "auth": { "token": { "id": "%s" } } }""" val uuidCheck = new Filter { // http://www.synnefo.org/docs/synnefo/latest/identity-api-guide.html#tokens-api-operations def postTokens(request: Request): Future[Response] = { val jsonFmt = postTokensJsonFmt val token = getPithosToken(request) val jsonPayload = jsonFmt.format(token) val url = tokensURL() val httpClient = FinagleClientFactory.newClientService(url) val postTokensRequest = RequestBuilder(). url(url). addHeader(StdHeader.Content_Type.headerName(), StdMediaType.Application_Json.value()). buildPost(Buf.ByteArray.Owned(jsonPayload.getBytes(StandardCharsets.UTF_8))) log.ifDebug(s"[postTokens] ==> POST $url") httpClient(postTokensRequest) } override def apply(request: Request, service: Service): Future[Response] = { if(isCdmiCapabilitiesUri(request.uri)) { return service(request) } getPithosUUID(request) match { case null if getPithosToken(request) ne null ⇒ postTokens(request).transform { case Return(postTokensResponse) if postTokensResponse.statusCode == 200 ⇒ val responseString = postTokensResponse.contentString val jsonTree = Json.jsonStringToTree(responseString) if(jsonTree.has("access")) { val accessTree = jsonTree.get("access") if(accessTree.has("token")) { val tokenTree = accessTree.get("token") if(tokenTree.has("tenant")) { val tenantTree = tokenTree.get("tenant") if(tenantTree.has("id")) { val idTree = tenantTree.get("id") if(idTree.isTextual) { val uuid = idTree.asText() request.headerMap.add(X_Pithos_UUID, uuid) log.info(s"[postTokens] <== 200 Derived $X_Pithos_UUID: $uuid") } } } } } else log.warning(s"[postTokens] <== 200 (unknown JSON)") getPithosUUID(request) match { case null ⇒ // still not found internalServerError( request, new Exception(s"Could not retrieve UUID from ${tokensURL()}"), PithosErrorRef.PIE001 ) case _ ⇒ service(request) } case Return(postTokensResponse) ⇒ // TODO Check the status we return textPlain(request, postTokensResponse.status, postTokensResponse.contentString) case Throw(t) ⇒ log.error(s"ERROR calling ${tokensURL()}") internalServerError(request, t, PithosErrorRef.PIE009) } case uuid if uuid ne null ⇒ log.info(s"Given $X_Pithos_UUID: $uuid") service(request) case _ ⇒ service(request) } } } val pithosHeadersFilter = new Filter { override def apply(request: Request, service: Service): Future[Response] = { // Pithos header check is needed only for URIs that result in calling Pithos if(isCdmiCapabilitiesUri(request.uri)) { return service(request) } val errorBuffer = new java.lang.StringBuilder() def addError(s: String): Unit = { if(errorBuffer.length() > 0) { errorBuffer.append('\\n') } errorBuffer.append(s) } val url = getPithosServerURL(request) val rootPath = getPithosRootPath(request) val uuid = getPithosUUID(request) val token = getPithosToken(request) if((url eq null) || url.isEmpty) { addError(s"No Pithos+ server URL. Please set header $X_Pithos_Server_URL") } if((rootPath eq null) || rootPath.isEmpty) { addError(s"No Pithos+ server root path. Please set header $X_Pithos_Root_Path") } if((uuid eq null) || uuid.isEmpty) { addError(s"No Pithos+ UUID. Please set header $X_Pithos_UUID") } if((token eq null) || token.isEmpty) { addError(s"No Pithos+ user token. Please set header $X_Pithos_Token or $X_Auth_Token") } if(errorBuffer.length() > 0) { badRequest( request, PithosErrorRef.PBR001, errorBuffer ) } else { service(request) } } } val myFilters = Vector(authFilter, uuidCheck, pithosHeadersFilter) override def mainFilters = super.mainFilters ++ myFilters override def flags: Seq[GlobalFlag[_]] = super.flags ++ Seq(pithosTimeout, pithosServerURL, pithosRootPath, authURL, authRedirect, tokensURL) def fixPathFromContentType(path: String, contentType: String): String = contentType match { case MediaTypes.Application_Directory | MediaTypes.Application_Folder ⇒ s"$path/" case MediaTypes.Application_CdmiContainer ⇒ s"$path/" case _ if contentType.startsWith(MediaTypes.Application_DirectorySemi) || contentType.startsWith(MediaTypes.Application_FolderSemi) ⇒ s"$path/" case _ ⇒ path } def transformResponse[T]( request: Request, resultF: Future[TResult[T]], errorRef: IErrorRef, onError: (TResult[T]) ⇒ Future[Response], onSuccess: (TResult[T]) ⇒ Future[Response] ): Future[Response] = { resultF.transform { case Return(result) if result.isSuccess ⇒ onSuccess(result) case Return(result) ⇒ onError(result) case Throw(t) ⇒ internalServerError(request, t, errorRef) } } /** * We delegate to `DELETE_object_cdmi`. * * @note The relevant sections from CDMI 1.0.2 are 8.8, 11.5 and 11.7. */ def DELETE_object_or_queue_or_queuevalue_cdmi(request: Request, path: List[String]): Future[StdCdmiPithosServer.Response] = { // We support only data objects DELETE_object_cdmi(request, path) } /** * Lists the contents of a container. */ override def GET_container_cdmi( request: Request, containerPath: List[String] ): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val folderPath = containerPath mkString "/" val pithosApi = pithos(serviceInfo) val checkResponseF = pithosApi.checkExistsObject(serviceInfo, folderPath) checkResponseF.transform { case Return(checkResult) if checkResult.isSuccess ⇒ val resultData = checkResult.successData.get if(resultData.isContainerOrDirectory) { val listResponseF = pithosApi.listObjectsInPath(serviceInfo, folderPath) listResponseF.transform { case Return(listResult) if listResult.isSuccess ⇒ val listObjectsInPath = listResult.successData.get.objects val children = for { oip ← listObjectsInPath } yield { // Pithos returns all the path part after the pithos container. // Note that Pithos container is not the same as CDMI container. log.debug(s"Child: '${oip.container}/${oip.path}' = ${oip.contentType}") val path = oip.path.lastIndexOf('/') match { case -1 ⇒ oip.path case i ⇒ oip.path.substring(i + 1) } fixPathFromContentType(path, oip.contentType) } val requestPath = request.path val parentPath = requestPath.parentPath val container = ContainerModel( objectID = requestPath, objectName = requestPath, parentURI = parentPath, parentID = parentPath, domainURI = "", childrenrange = Model.childrenRangeOf(children), children = children ) val jsonContainer = Json.objectToJsonString(container) okAppCdmiContainer(request, jsonContainer) case Return(listResult) ⇒ textPlain(request, listResult.status) case Throw(t) ⇒ internalServerError(request, t, PithosErrorRef.PIE002) } } else { notFound(request) } case Return(checkResult) ⇒ textPlain(request, checkResult.status, checkResult.errorDetails.getOrElse("")) case Throw(t) ⇒ internalServerError(request, t, PithosErrorRef.PIE011) } } def PUT_container_( request: Request, containerPath: List[String] ): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = containerPath mkString "/" // FIXME If the folder does not exist, the result here is just an empty folder val responseF = pithos(serviceInfo).createDirectory(serviceInfo, path) responseF.transform { case Return(result) if result.isSuccess ⇒ val requestPath = request.uri val parentPath = requestPath.parentPath val children = Seq() val container = ContainerModel( objectID = requestPath, objectName = requestPath, parentURI = parentPath, parentID = parentPath, domainURI = "", childrenrange = Model.childrenRangeOf(children), children = children ) val jsonContainer = Json.objectToJsonString(container) okAppCdmiContainer(request, jsonContainer) case Return(createDirectoryResponse) ⇒ badRequest( request, PithosErrorRef.PBR002, createDirectoryResponse.errorDetails.getOrElse("") ) case Throw(t) ⇒ internalServerError(request, t, PithosErrorRef.PIE003) } } /** * Creates a container using CDMI content type. * * @note Section 9.2 of CDMI 1.0.2: Create a Container Object using CDMI Content Type */ override def PUT_container_cdmi_create( request: Request, containerPath: List[String] ): Future[Response] = PUT_container_(request, containerPath) /** * Creates/updates a container using CDMI content type. * * @note Section 9.2 of CDMI 1.0.2: Create a Container Object using CDMI Content Type * @note Section 9.5 of CDMI 1.0.2: Update a Container Object using CDMI Content Type */ override def PUT_container_cdmi_create_or_update( request: Request, containerPath: List[String] ): Future[Response] = PUT_container_(request, containerPath) def DELETE_container_( request: Request, containerPath: List[String] ): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = containerPath mkString "/" val responseF = pithos(serviceInfo).deleteDirectory(serviceInfo, path) transformResponse[Unit]( request = request, resultF = responseF, errorRef = PithosErrorRef.PIE004, onError = result ⇒ textPlain(request, result.status, result.errorDetails.getOrElse("")), onSuccess = result ⇒ okTextPlain(request) ) } /** * Deletes a container using a CDMI content type. * * @note Section 9.6 of CDMI 1.0.2: Delete a Container Object using CDMI Content Type */ override def DELETE_container_cdmi( request: Request, containerPath: List[String] ): Future[Response] = DELETE_container_(request, containerPath) /** * Deletes a container using a non-CDMI content type. * * @note Section 9.7 of CDMI 1.0.2: Delete a Container Object using a Non-CDMI Content Type */ override def DELETE_container_noncdmi( request: Request, containerPath: List[String] ): Future[Response] = DELETE_container_(request, containerPath) def GET_object_( request: Request, objectPath: List[String] )(onSuccess: (GetObject2ResultData) ⇒ Future[Response]): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = objectPath mkString "/" val checkResponseF = pithos(serviceInfo).checkExistsObject(serviceInfo, path) transformResponse[CheckExistsObjectResultData]( request = request, resultF = checkResponseF, errorRef = PithosErrorRef.PIE012, onError = checkResult ⇒ textPlain(request, checkResult.status, checkResult.errorDetails.getOrElse("")), onSuccess = checkResult ⇒ { val resultData = checkResult.successData.get if(resultData.isContainerOrDirectory) { // This is a folder or container, not a file. Go away! notFound(request) } else { val objectResponseF = pithos(serviceInfo).getObject2(serviceInfo, path, null) transformResponse[GetObject2ResultData]( request = request, resultF = objectResponseF, errorRef = PithosErrorRef.PIE005, onError = objectResult ⇒ textPlain(request, objectResult.status), onSuccess = objectResult ⇒ onSuccess(objectResult.successData.get) ) } } ) } /** * Read a data object using CDMI content type. * * @note Section 8.4 of CDMI 1.0.2: Read a Data Object using CDMI Content Type */ override def GET_object_cdmi(request: Request, objectPath: List[String]): Future[Response] = { GET_object_(request, objectPath) { resultData ⇒ val contents = resultData.objBuf val contentsAsArray = Buf.ByteArray.Owned.extract(contents) val size = contents.length val contentType = resultData.Content_Type val requestPath = request.path val requestPathNoObjectIdPrefix = requestPath.removePrefix("/cdmi_objectid") val parentPath = requestPathNoObjectIdPrefix.parentPath val isTextPlain = contentType.exists(_.startsWith(MediaTypes.Text_Plain)) val value = if(isTextPlain) new String(contentsAsArray, StandardCharsets.UTF_8) else Base64.encodeArray(contentsAsArray) val vte = if(isTextPlain) "utf-8" else "base64" val model = ObjectModel( objectID = requestPathNoObjectIdPrefix, objectName = requestPathNoObjectIdPrefix, parentURI = parentPath, parentID = parentPath, domainURI = "", mimetype = contentType.getOrElse(""), metadata = Map(StorageSystemMetadata.cdmi_size.name() → size.toString), valuetransferencoding = vte, valuerange = s"0-${size - 1}", value = value ) val jsonModel = Json.objectToJsonString(model) okAppCdmiObject(request, jsonModel) } } /** * Read a data object using non-CDMI content type. * * @note Section 8.5 of CDMI 1.0.2: Read a Data Object using a Non-CDMI Content Type */ override def GET_object_noncdmi(request: Request, objectPath: List[String]): Future[Response] = { GET_object_(request, objectPath) { resultData ⇒ val status = Status.Ok val response = Response(request.version, status) response.content = resultData.objBuf resultData.Content_Type .foreach(response.contentType = _) resultData.Content_Length.foreach(response.contentLength = _) response.headerMap.add(HeaderNames.X_CDMI_Specification_Version, currentCdmiVersion) response.future } } /** * Create a data object in a container using CDMI content type. */ override def PUT_object_cdmi_create_or_update( request: Request, objectPath: List[String] ): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = objectPath mkString "/" val content = request.contentString val jsonTree = try Json.jsonStringToTree(content) catch { case e: com.fasterxml.jackson.core.JsonParseException ⇒ log.error(s"Error parsing input as JSON: $e") return badRequest( request, PithosErrorRef.PBR008, s"Could not parse input as JSON.\\n${e.getMessage}" ) } val mimeTypeNode = jsonTree.get("mimetype") val valueNode = jsonTree.get("value") val vteNode = jsonTree.get("valuetransferencoding") if((mimeTypeNode ne null) && !mimeTypeNode.isTextual) { return badRequest( request, PithosErrorRef.PBR003, s"Incorrect type ${mimeTypeNode.getNodeType} of 'mimetype' field. Should be ${JsonNodeType.STRING}" ) } if((vteNode ne null) && !vteNode.isTextual) { return badRequest( request, PithosErrorRef.PBR004, s"Incorrect type ${vteNode.getNodeType} of 'valuetransferencoding' field. Should be ${JsonNodeType.STRING}" ) } // Not mandated by the spec but we currently support only the presence of "value" if(valueNode eq null) { return badRequest( request, PithosErrorRef.PBR005, "'value' is not present" ) } if(!valueNode.isTextual) { return badRequest( request, PithosErrorRef.PBR006, s"Incorrect type ${valueNode.getNodeType} of 'value' field. Should be ${JsonNodeType.STRING}" ) } val mimetype = mimeTypeNode match { case null ⇒ MediaTypes.Text_Plain case _ ⇒ mimeTypeNode.asText() } val vte = vteNode match { case null ⇒ "utf-8" case node ⇒ node.asText().toLowerCase(Locale.US) match { case text @ ("utf-8" | "base64") ⇒ text case text ⇒ return badRequest( request, PithosErrorRef.PBR007, s"Incorrect value of 'valuetransferencoding' field [$text]" ) } } val bytes = valueNode.asText() match { case null ⇒ Array[Byte]() case utf8 if vte == "utf-8" ⇒ utf8.getBytes(vte) case base64 if vte == "base64" ⇒ Base64.decodeString(base64) } val putObjectResponseF = pithos(serviceInfo).putObject(serviceInfo, path, bytes, mimetype) transformResponse[Unit]( request = request, resultF = putObjectResponseF, errorRef = PithosErrorRef.PIE006, onError = result ⇒ textPlain(request, result.status, result.errorDetails.getOrElse("")), onSuccess = result ⇒ { val size = bytes.length val requestPath = request.path val requestPathNoObjectIdPrefix = requestPath.removePrefix("/cdmi_objectid") val parentPath = requestPathNoObjectIdPrefix.parentPath val valueRangeEnd = if(size == 0) 0 else size - 1 val model = ObjectModel( objectID = requestPath, objectName = requestPath, parentURI = parentPath, parentID = parentPath, domainURI = "", mimetype = mimetype, metadata = Map(StorageSystemMetadata.cdmi_size.name() → size.toString), valuetransferencoding = vte, valuerange = s"0-$valueRangeEnd", value = "" // TODO technically should not be present ) val jsonModel = Json.objectToJsonString(model) okJson(request, jsonModel) } ) } /** * Creates a data object in a container using CDMI content type. * * @note Section 8.2 of CDMI 1.0.2: Create a Data Object Using CDMI Content Type */ override def PUT_object_cdmi_create(request: Request, objectPath: List[String]): Future[Response] = PUT_object_cdmi_create_or_update(request, objectPath) /** * Create a data object in a container using non-CDMI content type. * The given `contentType` is guaranteed to be not null. */ override def PUT_object_noncdmi( request: Request, objectPath: List[String], contentType: String ): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = objectPath.mkString("/") val payload = request.content val responseF = pithos(serviceInfo).putObject(serviceInfo, path, payload, contentType) transformResponse[Unit]( request = request, resultF = responseF, errorRef = PithosErrorRef.PIE007, onError = result ⇒ textPlain(request, result.status, result.errorDetails.getOrElse("")), onSuccess = result ⇒ okTextPlain(request) ) } /** * Delete a data object (file). */ def DELETE_object_(request: Request, objectPath: List[String]): Future[Response] = { val serviceInfo = getPithosServiceInfo(request) val path = objectPath.mkString("/") val responseF = pithos(serviceInfo).deleteFile(serviceInfo, path) transformResponse[Unit]( request = request, resultF = responseF, errorRef = PithosErrorRef.PIE008, onError = result ⇒ textPlain(request, result.status, result.errorDetails.getOrElse("")), onSuccess = result ⇒ okTextPlain(request) ) } /** * Deletes a data object in a container using CDMI content type. * * @note Section 8.8 of CDMI 1.0.2: Delete a Data Object using CDMI Content Type */ override def DELETE_object_cdmi(request: Request, objectPath: List[String]): Future[Response] = DELETE_object_(request, objectPath) /** * Deletes a data object in a container using non-CDMI content type. * * @note Section 8.9 of CDMI 1.0.2: Delete a Data Object using a Non-CDMI Content Type */ override def DELETE_object_noncdmi(request: Request, objectPath: List[String]): Future[Response] = DELETE_object_(request, objectPath) }
grnet/snf-cdmi
src/main/scala/gr/grnet/cdmi/service/StdCdmiPithosServer.scala
Scala
gpl-3.0
28,506
package models import org.specs2.mutable._ import anorm._ import anorm.SqlParser import play.api.test._ import play.api.test.Helpers._ import helpers.InjectorSupport import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.db.Database import java.time.Instant class UserAddressSpec extends Specification with InjectorSupport { "User address" should { "Can create new record" in { implicit val app: Application = GuiceApplicationBuilder().configure(inMemoryDatabase()).build() val localeInfo = inject[LocaleInfoRepo] val currencyInfo = inject[CurrencyRegistry] inject[Database].withConnection { implicit conn => val user = inject[StoreUserRepo].create( userName = "uno", firstName = "", middleName = None, lastName = "", email = "", passwordHash = 0L, salt = 0L, userRole = UserRole.NORMAL, companyName = None ) val address01 = Address.createNew( countryCode = CountryCode.JPN ) val address02 = Address.createNew( countryCode = CountryCode.JPN ) val ua1 = UserAddress.createNew(user.id.get, address01.id.get) val ua2 = UserAddress.createNew(user.id.get, address02.id.get) ua1.seq === 1 ua2.seq === 2 } } "Can get by userid" in { implicit val app: Application = GuiceApplicationBuilder().configure(inMemoryDatabase()).build() val localeInfo = inject[LocaleInfoRepo] val currencyInfo = inject[CurrencyRegistry] inject[Database].withConnection { implicit conn => val user = inject[StoreUserRepo].create( userName = "uno", firstName = "", middleName = None, lastName = "", email = "", passwordHash = 0L, salt = 0L, userRole = UserRole.NORMAL, companyName = None ) val address01 = Address.createNew( countryCode = CountryCode.JPN ) val address02 = Address.createNew( countryCode = CountryCode.JPN ) val ua1 = UserAddress.createNew(user.id.get, address01.id.get) val ua2 = UserAddress.createNew(user.id.get, address02.id.get) val rec = UserAddress.getByUserId(user.id.get) rec.isDefined === true rec.get.storeUserId === user.id.get rec.get.addressId === address01.id.get rec.get.seq === 1 } } } }
ruimo/store2
test/models/UserAddressSpec.scala
Scala
apache-2.0
2,525
/* * Copyright (c) 2012 Crown Copyright * Animal Health and Veterinary Laboratories Agency * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sampler.data import sampler.math.Random import scala.collection.GenTraversableOnce /** Empirical implementation which is backed by an IndexedSeq. * * Ideal for collecting observations from continuous distributions or distributions * with few repeated values. */ class EmpiricalSeq[A](val values: IndexedSeq[A]) extends Empirical[A]{ self => lazy val size = values.size /** A map from each observation to the probability of seeing that value */ lazy val probabilityTable = { val sizeAsDouble = values.size.asInstanceOf[Double] values.groupBy(identity).map{case (k,v) => (k, v.size / sizeAsDouble)} } /** Returns a new Empirical containing all the observations in this instance plus those in the * more instance * * {{{ * val empSeq = new EmpiricalSeq(IndexedSeq(1,2,3,4)) * val more = IndexedSeq(5,6,7,8) * * empSeq ++ more * }}} * * @param more the observations to append * @return a new empirical containing all observations of this Empirical plus the observations in more */ def ++(more: GenTraversableOnce[A]) = new EmpiricalSeq(values ++ more) /** Creates a new [[sampler.data.Samplable]] from the distribution * * @return [[sampler.data.Samplable]] object */ def toDistribution(implicit r: Random): Distribution[A] = Distribution.uniform(values) override def canEqual(other: Any): Boolean = other.isInstanceOf[EmpiricalSeq[_]] }
tsaratoon/Sampler
sampler-core/src/main/scala/sampler/data/EmpiricalSeq.scala
Scala
apache-2.0
2,155
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.runtime.aggregate import org.apache.calcite.rel.`type`._ import org.apache.calcite.rel.RelCollation import org.apache.calcite.rel.RelFieldCollation import org.apache.calcite.rel.RelFieldCollation.Direction import org.apache.flink.types.Row import org.apache.flink.table.runtime.types.{CRow, CRowTypeInfo} import org.apache.flink.api.common.typeinfo.TypeInformation import org.apache.flink.api.common.ExecutionConfig import org.apache.flink.streaming.api.functions.ProcessFunction import org.apache.flink.api.common.typeutils.TypeComparator import org.apache.flink.api.java.typeutils.runtime.RowComparator import org.apache.flink.api.common.typeutils.TypeSerializer import org.apache.flink.api.common.typeinfo.AtomicType import org.apache.flink.table.api.TableException import org.apache.flink.table.calcite.FlinkTypeFactory import org.apache.flink.api.common.functions.MapFunction import org.apache.flink.table.plan.schema.RowSchema import org.apache.flink.util.Preconditions import java.util.Comparator import scala.collection.JavaConverters._ /** * Class represents a collection of helper methods to build the sort logic. * It encapsulates as well the implementation for ordering and generic interfaces */ object SortUtil { /** * Creates a ProcessFunction to sort rows based on event time and possibly other secondary fields. * * @param collationSort The list of sort collations. * @param inputType The row type of the input. * @param execCfg Execution configuration to configure comparators. * @return A function to sort stream values based on event-time and secondary sort fields. */ private[flink] def createRowTimeSortFunction( collationSort: RelCollation, inputType: RelDataType, inputTypeInfo: TypeInformation[Row], execCfg: ExecutionConfig): ProcessFunction[CRow, CRow] = { Preconditions.checkArgument(collationSort.getFieldCollations.size() > 0) val rowtimeIdx = collationSort.getFieldCollations.get(0).getFieldIndex val collectionRowComparator = if (collationSort.getFieldCollations.size() > 1) { val rowComp = createRowComparator( inputType, collationSort.getFieldCollations.asScala.tail, // strip off time collation execCfg) Some(new CollectionRowComparator(rowComp)) } else { None } val inputCRowType = CRowTypeInfo(inputTypeInfo) new RowTimeSortProcessFunction( inputCRowType, rowtimeIdx, collectionRowComparator) } /** * Creates a ProcessFunction to sort rows based on processing time and additional fields. * * @param collationSort The list of sort collations. * @param inputType The row type of the input. * @param execCfg Execution configuration to configure comparators. * @return A function to sort stream values based on proctime and other secondary sort fields. */ private[flink] def createProcTimeSortFunction( collationSort: RelCollation, inputType: RelDataType, inputTypeInfo: TypeInformation[Row], execCfg: ExecutionConfig): ProcessFunction[CRow, CRow] = { val rowComp = createRowComparator( inputType, collationSort.getFieldCollations.asScala.tail, // strip off time collation execCfg) val collectionRowComparator = new CollectionRowComparator(rowComp) val inputCRowType = CRowTypeInfo(inputTypeInfo) new ProcTimeSortProcessFunction( inputCRowType, collectionRowComparator) } /** * Creates a RowComparator for the provided field collations and input type. * * @param inputType the row type of the input. * @param fieldCollations the field collations * @param execConfig the execution configuration. * * @return A RowComparator for the provided sort collations and input type. */ private def createRowComparator( inputType: RelDataType, fieldCollations: Seq[RelFieldCollation], execConfig: ExecutionConfig): RowComparator = { val sortFields = fieldCollations.map(_.getFieldIndex) val sortDirections = fieldCollations.map(_.direction).map { case Direction.ASCENDING => true case Direction.DESCENDING => false case _ => throw new TableException("SQL/Table does not support such sorting") } val fieldComps = for ((k, o) <- sortFields.zip(sortDirections)) yield { FlinkTypeFactory.toTypeInfo(inputType.getFieldList.get(k).getType) match { case a: AtomicType[_] => a.createComparator(o, execConfig).asInstanceOf[TypeComparator[AnyRef]] case x: TypeInformation[_] => throw new TableException(s"Unsupported field type $x to sort on.") } } new RowComparator( new RowSchema(inputType).arity, sortFields.toArray, fieldComps.toArray, new Array[TypeSerializer[AnyRef]](0), // not required because we only compare objects. sortDirections.toArray) } /** * Returns the direction of the first sort field. * * @param collationSort The list of sort collations. * @return The direction of the first sort field. */ def getFirstSortDirection(collationSort: RelCollation): Direction = { Preconditions.checkArgument(collationSort.getFieldCollations.size() > 0) collationSort.getFieldCollations.get(0).direction } /** * Returns the first sort field. * * @param collationSort The list of sort collations. * @param rowType The row type of the input. * @return The first sort field. */ def getFirstSortField(collationSort: RelCollation, rowType: RelDataType): RelDataTypeField = { Preconditions.checkArgument(collationSort.getFieldCollations.size() > 0) val idx = collationSort.getFieldCollations.get(0).getFieldIndex rowType.getFieldList.get(idx) } } /** * Wrapper for Row TypeComparator to a Java Comparator object */ class CollectionRowComparator( private val rowComp: TypeComparator[Row]) extends Comparator[Row] with Serializable { override def compare(arg0:Row, arg1:Row):Int = { rowComp.compare(arg0, arg1) } } /** * Identity map for forwarding the fields based on their arriving times */ private[flink] class IdentityCRowMap extends MapFunction[CRow,CRow] { override def map(value:CRow):CRow ={ value } }
yew1eb/flink
flink-libraries/flink-table/src/main/scala/org/apache/flink/table/runtime/aggregate/SortUtil.scala
Scala
apache-2.0
7,093
/* * Copyright 2014 Twitter Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.zipkin.storage.util import com.twitter.conversions.time._ import com.twitter.logging.Logger import com.twitter.util.{Await, Duration, NonFatal} import com.twitter.zipkin.common._ import com.twitter.zipkin.query.Trace import com.twitter.zipkin.storage.{TraceIdDuration, SpanStore} import java.nio.ByteBuffer import scala.language.reflectiveCalls class SpanStoreValidator( newSpanStore: => SpanStore, ignoreSortTests: Boolean = false, log: Logger = Logger.get("ValidateSpanStore") ) { val ep = Endpoint(123, 123, "service") implicit def long2String(l: Long): String = l.toString def binaryAnnotation(key: String, value: String) = BinaryAnnotation(key, ByteBuffer.wrap(value.getBytes), AnnotationType.String, Some(ep)) val spanId = 456 val ann1 = Annotation(1, "cs", Some(ep)) val ann2 = Annotation(2, "sr", None) val ann3 = Annotation(20, "custom", Some(ep)) val ann4 = Annotation(20, "custom", Some(ep)) val ann5 = Annotation(5, "custom", Some(ep)) val ann6 = Annotation(6, "custom", Some(ep)) val ann7 = Annotation(7, "custom", Some(ep)) val ann8 = Annotation(8, "custom", Some(ep)) val span1 = Span(123, "methodcall", spanId, None, List(ann1, ann3), List(binaryAnnotation("BAH", "BEH"))) val span2 = Span(456, "methodcall", spanId, None, List(ann2), List(binaryAnnotation("BAH2", "BEH2"))) val span3 = Span(789, "methodcall", spanId, None, List(ann2, ann3, ann4), List(binaryAnnotation("BAH2", "BEH2"))) val span4 = Span(999, "methodcall", spanId, None, List(ann6, ann7), List()) val span5 = Span(999, "methodcall", spanId, None, List(ann5, ann8), List(binaryAnnotation("BAH2", "BEH2"))) val spanEmptySpanName = Span(123, "", spanId, None, List(ann1, ann2), List()) val spanEmptyServiceName = Span(123, "spanname", spanId, None, List(), List()) val mergedSpan = Span(123, "methodcall", spanId, None, List(ann1, ann2), List(binaryAnnotation("BAH2", "BEH2"))) def resetAndLoadStore(spans: Seq[Span]): SpanStore = { val store = newSpanStore Await.result(store(spans)) store } private[this] var tests: Map[String, (() => Unit)] = Map.empty private[this] def test(name: String)(f: => Unit) { tests += (name -> f _) } def validate { val spanStoreName = newSpanStore.getClass.getName.split('.').last val results = tests map { case (name, f) => println("validating %s: %s".format(spanStoreName, name)) try { f(); println(" pass") true } catch { case NonFatal(e) => println(" fail") log.error(e, "validation failed") false } } val passedCount = results.count(x => x) println("%d / %d passed.".format(passedCount, tests.size)) if (passedCount < tests.size) { println("Failed tests for %s:".format(spanStoreName)) results.zip(tests) collect { case (result, (name, _)) if !result => println(name) } } assert(passedCount == tests.size) } // Test that we handle failures correctly. def validateFailures { val spanStoreName = newSpanStore.getClass.getName.split('.').last val results = tests map { case (name, f) => println("validating failures with %s: %s".format(spanStoreName, name)) try { f() println(" Fail: exception not thrown.") log.error("Validation failed: exception not thrown.") false } catch { case e: SpanStoreException => println(" Caught exception %s (expected)".format(e)) true case NonFatal(x) => println(" Error: caught exception %s (unexpected)".format(x)) false } } val passedCount = results.count(x => x) println("%d / %d passed.".format(passedCount, tests.size)) if (passedCount < tests.size) { println("Failed tests for %s:".format(spanStoreName)) results.zip(tests) collect { case (result, (name, _)) if !result => println(name) } } assert(passedCount == tests.size) } def eq(a: Any, b: Any): Boolean = if (a == b) true else { println("%s is not equal to %s".format(a, b)) false } def empty(v: { def isEmpty: Boolean }): Boolean = if (v.isEmpty) true else { println("%s is not empty".format(v)) false } def notEmpty(v: { def isEmpty: Boolean }): Boolean = if (!v.isEmpty) true else { println("%s is empty".format(v)) false } test("get by trace id") { val store = resetAndLoadStore(Seq(span1)) val spans = Await.result(store.getSpansByTraceId(span1.traceId)) assert(eq(spans.size, 1)) assert(eq(spans.head, span1)) } test("get by trace ids") { val span666 = Span(666, "methodcall2", spanId, None, List(ann2), List(binaryAnnotation("BAH2", "BEH2"))) val store = resetAndLoadStore(Seq(span1, span666)) val actual1 = Await.result(store.getSpansByTraceIds(Seq(span1.traceId))) assert(notEmpty(actual1)) val trace1 = Trace(actual1(0)) assert(notEmpty(trace1.spans)) assert(eq(trace1.spans(0), span1)) val actual2 = Await.result(store.getSpansByTraceIds(Seq(span1.traceId, span666.traceId))) assert(eq(actual2.size, 2)) val trace2 = Trace(actual2(0)) assert(notEmpty(trace2.spans)) assert(eq(trace2.spans(0), span1)) val trace3 = Trace(actual2(1)) assert(notEmpty(trace3.spans)) assert(eq(trace3.spans(0), span666)) } test("get by trace ids returns an empty list if nothing is found") { val store = resetAndLoadStore(Seq()) val spans = Await.result(store.getSpansByTraceIds(Seq(54321))) // Nonexistent span assert(empty(spans)) } test("alter TTL on a span") { val store = resetAndLoadStore(Seq(span1)) Await.result(store.setTimeToLive(span1.traceId, 1234.seconds)) // If a store doesn't use TTLs this should return Duration.Top val allowedVals = Seq(1234.seconds, Duration.Top) assert(allowedVals.contains(Await.result(store.getTimeToLive(span1.traceId)))) } test("check for existing traces") { val store = resetAndLoadStore(Seq(span1, span4)) val expected = Set(span1.traceId, span4.traceId) val result = Await.result(store.tracesExist(Seq(span1.traceId, span4.traceId, 111111))) assert(eq(result, expected)) } test("get spans by name") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getSpanNames("service")), Set(span1.name))) } test("get service names") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getAllServiceNames), span1.serviceNames)) } if (!ignoreSortTests) { test("get trace ids by name") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getTraceIdsByName("service", None, 100, 3)).head.traceId, span1.traceId)) assert(eq(Await.result(store.getTraceIdsByName("service", Some("methodcall"), 100, 3)).head.traceId, span1.traceId)) assert(empty(Await.result(store.getTraceIdsByName("badservice", None, 100, 3)))) assert(empty(Await.result(store.getTraceIdsByName("service", Some("badmethod"), 100, 3)))) assert(empty(Await.result(store.getTraceIdsByName("badservice", Some("badmethod"), 100, 3)))) } test("get traces duration") { val store = resetAndLoadStore(Seq(span1, span2, span3, span4)) val expected = Seq( TraceIdDuration(span1.traceId, 19, 1), TraceIdDuration(span2.traceId, 0, 2), TraceIdDuration(span3.traceId, 18, 2), TraceIdDuration(span4.traceId, 1, 6)) val result = Await.result(store.getTracesDuration( Seq(span1.traceId, span2.traceId, span3.traceId, span4.traceId))) assert(eq(result, expected)) val store2 = resetAndLoadStore(Seq(span4)) assert(eq(Await.result(store2.getTracesDuration(Seq(999))), Seq(TraceIdDuration(999, 1, 6)))) Await.result(store2(Seq(span5))) assert(eq(Await.result(store2.getTracesDuration(Seq(999))), Seq(TraceIdDuration(999, 3, 5)))) } } test("get trace ids by annotation") { val store = resetAndLoadStore(Seq(span1)) // fetch by time based annotation, find trace val res1 = Await.result(store.getTraceIdsByAnnotation("service", "custom", None, 100, 3)) assert(eq(res1.head.traceId, span1.traceId)) // should not find any traces since the core annotation doesn't exist in index val res2 = Await.result(store.getTraceIdsByAnnotation("service", "cs", None, 100, 3)) assert(empty(res2)) // should find traces by the key and value annotation val res3 = Await.result(store.getTraceIdsByAnnotation("service", "BAH", Some(ByteBuffer.wrap("BEH".getBytes)), 100, 3)) assert(eq(res3.head.traceId, span1.traceId)) } test("limit on annotations") { val store = resetAndLoadStore(Seq(span1, span4, span5)) val res1 = Await.result(store.getTraceIdsByAnnotation("service", "custom", None, 100, limit = 2)) assert(eq(res1.length, 2)) assert(eq(res1(0).traceId, span1.traceId)) assert(eq(res1(1).traceId, span5.traceId)) } test("wont index empty service names") { val store = resetAndLoadStore(Seq(spanEmptyServiceName)) assert(empty(Await.result(store.getAllServiceNames))) } test("wont index empty span names") { val store = resetAndLoadStore(Seq(spanEmptySpanName)) assert(empty(Await.result(store.getSpanNames(spanEmptySpanName.name)))) } }
cogitate/twitter-zipkin-uuid
zipkin-common/src/main/scala/com/twitter/zipkin/storage/util/SpanStoreValidator.scala
Scala
apache-2.0
9,947
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.deploy.k8s.features import scala.collection.JavaConverters._ import io.fabric8.kubernetes.api.model._ import org.apache.spark.{SecurityManager, SparkConf, SparkException} import org.apache.spark.deploy.k8s._ import org.apache.spark.deploy.k8s.Config._ import org.apache.spark.deploy.k8s.Constants._ import org.apache.spark.internal.config._ import org.apache.spark.internal.config.Python._ import org.apache.spark.rpc.RpcEndpointAddress import org.apache.spark.scheduler.cluster.CoarseGrainedSchedulerBackend import org.apache.spark.util.Utils private[spark] class BasicExecutorFeatureStep( kubernetesConf: KubernetesExecutorConf, secMgr: SecurityManager) extends KubernetesFeatureConfigStep { // Consider moving some of these fields to KubernetesConf or KubernetesExecutorSpecificConf private val executorContainerImage = kubernetesConf .get(EXECUTOR_CONTAINER_IMAGE) .getOrElse(throw new SparkException("Must specify the executor container image")) private val blockManagerPort = kubernetesConf .sparkConf .getInt("spark.blockmanager.port", DEFAULT_BLOCKMANAGER_PORT) private val executorPodNamePrefix = kubernetesConf.resourceNamePrefix private val driverUrl = RpcEndpointAddress( kubernetesConf.get(DRIVER_HOST_ADDRESS), kubernetesConf.sparkConf.getInt(DRIVER_PORT.key, DEFAULT_DRIVER_PORT), CoarseGrainedSchedulerBackend.ENDPOINT_NAME).toString private val executorMemoryMiB = kubernetesConf.get(EXECUTOR_MEMORY) private val executorMemoryString = kubernetesConf.get( EXECUTOR_MEMORY.key, EXECUTOR_MEMORY.defaultValueString) private val memoryOverheadMiB = kubernetesConf .get(EXECUTOR_MEMORY_OVERHEAD) .getOrElse(math.max( (kubernetesConf.get(MEMORY_OVERHEAD_FACTOR) * executorMemoryMiB).toInt, MEMORY_OVERHEAD_MIN_MIB)) private val executorMemoryWithOverhead = executorMemoryMiB + memoryOverheadMiB private val executorMemoryTotal = if (kubernetesConf.get(APP_RESOURCE_TYPE) == Some(APP_RESOURCE_TYPE_PYTHON)) { executorMemoryWithOverhead + kubernetesConf.get(PYSPARK_EXECUTOR_MEMORY).map(_.toInt).getOrElse(0) } else { executorMemoryWithOverhead } private val executorCores = kubernetesConf.sparkConf.get(EXECUTOR_CORES) private val executorCoresRequest = if (kubernetesConf.sparkConf.contains(KUBERNETES_EXECUTOR_REQUEST_CORES)) { kubernetesConf.get(KUBERNETES_EXECUTOR_REQUEST_CORES).get } else { executorCores.toString } private val executorLimitCores = kubernetesConf.get(KUBERNETES_EXECUTOR_LIMIT_CORES) override def configurePod(pod: SparkPod): SparkPod = { val name = s"$executorPodNamePrefix-exec-${kubernetesConf.executorId}" // hostname must be no longer than 63 characters, so take the last 63 characters of the pod // name as the hostname. This preserves uniqueness since the end of name contains // executorId val hostname = name.substring(Math.max(0, name.length - 63)) // Remove non-word characters from the start of the hostname .replaceAll("^[^\\\\w]+", "") // Replace dangerous characters in the remaining string with a safe alternative. .replaceAll("[^\\\\w-]+", "_") val executorMemoryQuantity = new QuantityBuilder(false) .withAmount(s"${executorMemoryTotal}Mi") .build() val executorCpuQuantity = new QuantityBuilder(false) .withAmount(executorCoresRequest) .build() val executorResourceQuantities = KubernetesUtils.buildResourcesQuantities(SPARK_EXECUTOR_PREFIX, kubernetesConf.sparkConf) val executorEnv: Seq[EnvVar] = { (Seq( (ENV_DRIVER_URL, driverUrl), (ENV_EXECUTOR_CORES, executorCores.toString), (ENV_EXECUTOR_MEMORY, executorMemoryString), (ENV_APPLICATION_ID, kubernetesConf.appId), // This is to set the SPARK_CONF_DIR to be /opt/spark/conf (ENV_SPARK_CONF_DIR, SPARK_CONF_DIR_INTERNAL), (ENV_EXECUTOR_ID, kubernetesConf.executorId) ) ++ kubernetesConf.environment).map { case (k, v) => new EnvVarBuilder() .withName(k) .withValue(v) .build() } } ++ { Seq(new EnvVarBuilder() .withName(ENV_EXECUTOR_POD_IP) .withValueFrom(new EnvVarSourceBuilder() .withNewFieldRef("v1", "status.podIP") .build()) .build()) } ++ { if (kubernetesConf.get(AUTH_SECRET_FILE_EXECUTOR).isEmpty) { Option(secMgr.getSecretKey()).map { authSecret => new EnvVarBuilder() .withName(SecurityManager.ENV_AUTH_SECRET) .withValue(authSecret) .build() } } else None } ++ { kubernetesConf.get(EXECUTOR_CLASS_PATH).map { cp => new EnvVarBuilder() .withName(ENV_CLASSPATH) .withValue(cp) .build() } } ++ { val userOpts = kubernetesConf.get(EXECUTOR_JAVA_OPTIONS).toSeq.flatMap { opts => val subsOpts = Utils.substituteAppNExecIds(opts, kubernetesConf.appId, kubernetesConf.executorId) Utils.splitCommandString(subsOpts) } val sparkOpts = Utils.sparkJavaOpts(kubernetesConf.sparkConf, SparkConf.isExecutorStartupConf) (userOpts ++ sparkOpts).zipWithIndex.map { case (opt, index) => new EnvVarBuilder() .withName(s"$ENV_JAVA_OPT_PREFIX$index") .withValue(opt) .build() } } val requiredPorts = Seq( (BLOCK_MANAGER_PORT_NAME, blockManagerPort)) .map { case (name, port) => new ContainerPortBuilder() .withName(name) .withContainerPort(port) .build() } val executorContainer = new ContainerBuilder(pod.container) .withName(Option(pod.container.getName).getOrElse(DEFAULT_EXECUTOR_CONTAINER_NAME)) .withImage(executorContainerImage) .withImagePullPolicy(kubernetesConf.imagePullPolicy) .editOrNewResources() .addToRequests("memory", executorMemoryQuantity) .addToLimits("memory", executorMemoryQuantity) .addToRequests("cpu", executorCpuQuantity) .addToLimits(executorResourceQuantities.asJava) .endResources() .addNewEnv() .withName(ENV_SPARK_USER) .withValue(Utils.getCurrentUserName()) .endEnv() .addAllToEnv(executorEnv.asJava) .withPorts(requiredPorts.asJava) .addToArgs("executor") .build() val containerWithLimitCores = executorLimitCores.map { limitCores => val executorCpuLimitQuantity = new QuantityBuilder(false) .withAmount(limitCores) .build() new ContainerBuilder(executorContainer) .editResources() .addToLimits("cpu", executorCpuLimitQuantity) .endResources() .build() }.getOrElse(executorContainer) val ownerReference = kubernetesConf.driverPod.map { pod => new OwnerReferenceBuilder() .withController(true) .withApiVersion(pod.getApiVersion) .withKind(pod.getKind) .withName(pod.getMetadata.getName) .withUid(pod.getMetadata.getUid) .build() } val executorPod = new PodBuilder(pod.pod) .editOrNewMetadata() .withName(name) .addToLabels(kubernetesConf.labels.asJava) .addToAnnotations(kubernetesConf.annotations.asJava) .addToOwnerReferences(ownerReference.toSeq: _*) .endMetadata() .editOrNewSpec() .withHostname(hostname) .withRestartPolicy("Never") .addToNodeSelector(kubernetesConf.nodeSelector.asJava) .addToImagePullSecrets(kubernetesConf.imagePullSecrets: _*) .endSpec() .build() kubernetesConf.get(KUBERNETES_EXECUTOR_SCHEDULER_NAME) .foreach(executorPod.getSpec.setSchedulerName) SparkPod(executorPod, containerWithLimitCores) } }
caneGuy/spark
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/deploy/k8s/features/BasicExecutorFeatureStep.scala
Scala
apache-2.0
8,790
package gsn.data.rdf import gsn.data._ import com.hp.hpl.jena.rdf.model.Model import com.hp.hpl.jena.rdf.model.ModelFactory import gsn.vocab.Ssn import com.hp.hpl.jena.vocabulary.RDF import com.hp.hpl.jena.vocabulary.RDFS import com.hp.hpl.jena.vocabulary.DCTerms import gsn.vocab.Qu import com.hp.hpl.jena.rdf.model.ResourceFactory import gsn.vocab.QuUnit class SsnModel { val pref="http://example.com/ns#" val dbfield=ResourceFactory.createProperty(pref+"dateField") def toRdf(s:Sensor)={ val m:Model = ModelFactory.createDefaultModel val sensorId=m.createResource(pref+s.name) m.add(sensorId, RDF.`type`, Ssn.Sensor) m.add(sensorId,DCTerms.identifier,s.name) //m.add() s.implements.foreach{sensing=> sensing.outputs.foreach{field=> val proc=m.createResource(pref+"proc"+s.name+"/"+field.fieldName ) val output=m.createResource(pref+"output"+s.name+"/"+field.fieldName ) m.add(sensorId,Ssn.implements_,proc) m.add(proc,Ssn.forProperty,sensing.obsProperty ) m.add(output,dbfield,field.fieldName ) m.add(output,Qu.unit,field.unit.code ) m.add(proc,Ssn.hasOutput,output) } } m.write(System.out) } }
TheCroak/gsn
gsn-tools/src/main/scala/gsn/data/rdf/SsnModel.scala
Scala
gpl-3.0
1,203
trait ElementSeed { val elementType: String def buildLayer(height, width, scale) }
KeithCissell/SCOUt
THESIS/Latex-Template/tex/codes/ElementSeed.scala
Scala
mit
87
package com.bolour.boardgame.scala.server.service import spray.json._ import com.bolour.boardgame.scala.server.domain.{Game, Player} import com.bolour.util.scala.common.CommonUtil.ID import com.bolour.boardgame.scala.server.domain.json.CaseClassFormats._ import com.bolour.boardgame.scala.server.service.json.CaseClassFormats._ import com.bolour.util.scala.common.VersionStamped import scala.util.{Failure, Success, Try} /** * Implementation of the hig-level game persister interface using a JSON persister. * Converts objects to their JSON representations and calls lower-level JSON * persister to persist them. * * @param jsonPersister The specific lower-level JSON persister to use. * @param version The server version - in case JSON representations change over time. */ class GamePersisterJsonBridge(jsonPersister: GameJsonPersister, version: Int) extends GamePersister { override def migrate() = jsonPersister.migrate() override def clearGames() = jsonPersister.clearGames() override def clearPlayers() = jsonPersister.clearPlayers() override def savePlayer(player: Player) = { val versionedPlayer = VersionStamped[Player](version, player) val json = versionedPlayer.toJson.prettyPrint jsonPersister.savePlayer(player.id, player.name, json) } override def findPlayerByName(name: String) = { for { ojson <- jsonPersister.findPlayerByName(name) oplayer = ojson map { json => val jsonAst = json.parseJson val versionedPlayer = jsonAst.convertTo[VersionStamped[Player]] versionedPlayer.data } } yield oplayer } override def saveGame(gameData: GameData): Try[Unit] = { val versionedGameData = VersionStamped[GameData](version, gameData) val gameId = gameData.base.gameId val playerId = gameData.base.playerId val json = versionedGameData.toJson.prettyPrint // TODO. Game should expose id itself. jsonPersister.saveGame(gameId, playerId, json) } override def findGameById(gameId: ID) = { for { ojson <- jsonPersister.findGameById(gameId) odata = ojson map { json => val jsonAst = json.parseJson val versionedData = jsonAst.convertTo[VersionStamped[GameData]] versionedData.data } } yield odata } override def deleteGame(gameId: ID) = jsonPersister.deleteGame(gameId) }
azadbolour/boardgame
scala-server/app/com/bolour/boardgame/scala/server/service/GamePersisterJsonBridge.scala
Scala
agpl-3.0
2,354
package com.twitter.inject.thrift.filtered_integration.http_server import com.twitter.finatra.http.HttpServer import com.twitter.finatra.http.filters.CommonFilters import com.twitter.finatra.http.routing.HttpRouter import com.twitter.inject.thrift.ThriftClientIdModule class GreeterHttpServer extends HttpServer { override val name = "greeter-server" override val modules = Seq( ThriftClientIdModule, GreeterThriftClientModule) override def configureHttp(router: HttpRouter) { router. filter[CommonFilters]. add[GreeterHttpController] } }
joecwu/finatra
inject/inject-thrift-client/src/test/scala/com/twitter/inject/thrift/filtered_integration/http_server/GreeterHttpServer.scala
Scala
apache-2.0
575
package gh2011.models case class SHA(id: Option[String], mail: Option[String], message: Option[String])
mgoeminne/github_etl
src/main/scala/gh2011/models/SHA.scala
Scala
mit
105
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.audit.serialiser import play.api.libs.json.{JsObject, JsString, JsValue, Json, Writes} import uk.gov.hmrc.play.audit.model.{DataCall, DataEvent, ExtendedDataEvent, MergedDataEvent} import java.time.{Instant, ZoneId} import java.time.format.DateTimeFormatter object DateWriter { // Datastream does not support default X offset (i.e. `Z` must be `+0000`) implicit def instantWrites = new Writes[Instant] { private val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ") def writes(instant: Instant): JsValue = JsString(dateFormat.withZone(ZoneId.of("UTC")).format(instant)) } } trait AuditSerialiserLike { def serialise(event: DataEvent): JsObject def serialise(event: ExtendedDataEvent): JsObject def serialise(event: MergedDataEvent): JsObject } class AuditSerialiser extends AuditSerialiserLike { private implicit val dateWriter: Writes[Instant] = DateWriter.instantWrites private implicit val dataEventWriter: Writes[DataEvent] = Json.writes[DataEvent] private implicit val dataCallWriter: Writes[DataCall] = Json.writes[DataCall] private implicit val extendedDataEventWriter: Writes[ExtendedDataEvent] = Json.writes[ExtendedDataEvent] private implicit val mergedDataEventWriter: Writes[MergedDataEvent] = Json.writes[MergedDataEvent] override def serialise(event: DataEvent): JsObject = Json.toJson(event).as[JsObject] override def serialise(event: ExtendedDataEvent): JsObject = Json.toJson(event).as[JsObject] override def serialise(event: MergedDataEvent): JsObject = Json.toJson(event).as[JsObject] } object AuditSerialiser extends AuditSerialiser
hmrc/play-auditing
src-common/main/scala/uk/gov/hmrc/audit/serialiser/AuditSerialiser.scala
Scala
apache-2.0
2,262
package spgui.widgets.services import java.util.UUID import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.html_<^._ import spgui.communication._ import sp.domain._ import sp.domain.Logic._ object ServiceListWidget { case class State(services: List[APISP.StatusResponse]) private class Backend($: BackendScope[Unit, State]) { import spgui.widgets.services.{APIServiceHandler => api} def handelMess(mess: SPMessage): Unit = { ServiceWidgetComm.extractResponse(mess).map{ case (h, b) => val res = b match { case api.Services(xs) => $.setState(State(xs)) case api.NewService(s) => $.modState(state => State(s :: state.services)) case api.RemovedService(s) => $.modState(state => State(state.services.filter(x => x.service != s.service))) } res.runNow() } } val answerHandler = BackendCommunication.getMessageObserver(handelMess, "answers") val speventHandler = BackendCommunication.getMessageObserver(handelMess, "spevents") def render(s: State) = { <.div( renderServices(s), <.div("todo: Add search and sorting. Add possibility to send messaged based on api") ) } def renderServices(s: State) = { <.table( ^.className := "table table-striped", <.caption("Services"), <.thead( <.th("service"), <.th("name"), <.th("id"), <.th("tags"), <.th("api"), <.th("version") ), <.tbody( s.services.map(s=> { <.tr( <.td(s.service), <.td(s.instanceName), <.td(s.instanceID.toString), <.td(s.tags.toString), <.td(s.api.toString()), <.td(s.version) ) }).toTagMod ) ) } def onUnmount() = { answerHandler.kill() speventHandler.kill() Callback.empty } def onMount() = { sendToHandler(api.GetServices) } def sendToHandler(mess: api.Request): Callback = { val h = SPHeader(from = "ServiceListWidget", to = api.service, reply = SPValue("ServiceListWidget"), reqID = java.util.UUID.randomUUID()) val json = ServiceWidgetComm.makeMess(h, mess) BackendCommunication.publish(json, "services") Callback.empty } } private val component = ScalaComponent.builder[Unit]("AbilityHandlerWidget") .initialState(State(services = List())) .renderBackend[Backend] .componentDidMount(_.backend.onMount()) .componentWillUnmount(_.backend.onUnmount()) .build def apply() = spgui.SPWidget(spwb => component()) }
kristoferB/SP
gui/src/main/scala/spgui/widgets/services/ServiceListWidget.scala
Scala
mit
2,701
package models.data import scalikejdbc._ case class Approver(id: Long, name: String, email: String) object Approver extends SQLSyntaxSupport[Approver] { override val tableName = "approver" def apply(a: ResultName[Approver])(rs: WrappedResultSet): Approver = new Approver(rs.long(a.id), rs.string(a.name), rs.string(a.email)) }
codingteam/loglist
scalajvm/app/models/data/Approver.scala
Scala
mit
337
/* __ *\\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\\ \\/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\\___/_/ |_/____/_/ | | ** ** |/ ** \\* */ package scala package util package control import scala.reflect.{ ClassTag, classTag } import scala.language.implicitConversions /** Classes representing the components of exception handling. * * Each class is independently composable. * * This class differs from [[scala.util.Try]] in that it focuses on composing exception handlers rather than * composing behavior. All behavior should be composed first and fed to a [[Catch]] object using one of the * `opt`, `either` or `withTry` methods. Taken together the classes provide a DSL for composing catch and finally * behaviors. * * === Examples === * * Create a `Catch` which handles specified exceptions. * {{{ * import scala.util.control.Exception._ * import java.net._ * * val s = "http://www.scala-lang.org/" * * // Some(http://www.scala-lang.org/) * val x1: Option[URL] = catching(classOf[MalformedURLException]) opt new URL(s) * * // Right(http://www.scala-lang.org/) * val x2: Either[Throwable,URL] = * catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s) * * // Success(http://www.scala-lang.org/) * val x3: Try[URL] = catching(classOf[MalformedURLException], classOf[NullPointerException]) withTry new URL(s) * * val defaultUrl = new URL("http://example.com") * // URL(http://example.com) because htt/xx throws MalformedURLException * val x4: URL = failAsValue(classOf[MalformedURLException])(defaultUrl)(new URL("htt/xx")) * }}} * * Create a `Catch` which logs exceptions using `handling` and `by`. * {{{ * def log(t: Throwable): Unit = t.printStackTrace * * val withThrowableLogging: Catch[Unit] = handling(classOf[MalformedURLException]) by (log) * * def printUrl(url: String) : Unit = { * val con = new URL(url) openConnection() * val source = scala.io.Source.fromInputStream(con.getInputStream()) * source.getLines.foreach(println) * } * * val badUrl = "htt/xx" * // Prints stacktrace, * // java.net.MalformedURLException: no protocol: htt/xx * // at java.net.URL.<init>(URL.java:586) * withThrowableLogging { printUrl(badUrl) } * * val goodUrl = "http://www.scala-lang.org/" * // Prints page content, * // &lt;!DOCTYPE html&gt; * // &lt;html&gt; * withThrowableLogging { printUrl(goodUrl) } * }}} * * Use `unwrapping` to create a `Catch` that unwraps exceptions before rethrowing. * {{{ * class AppException(cause: Throwable) extends RuntimeException(cause) * * val unwrappingCatch: Catch[Nothing] = unwrapping(classOf[AppException]) * * def calcResult: Int = throw new AppException(new NullPointerException) * * // Throws NPE not AppException, * // java.lang.NullPointerException * // at .calcResult(&lt;console&gt;:17) * val result = unwrappingCatch(calcResult) * }}} * * Use `failAsValue` to provide a default when a specified exception is caught. * * {{{ * val inputDefaulting: Catch[Int] = failAsValue(classOf[NumberFormatException])(0) * val candidatePick = "seven" // scala.io.StdIn.readLine() * * // Int = 0 * val pick = inputDefaulting(candidatePick.toInt) * }}} * * Compose multiple `Catch`s with `or` to build a `Catch` that provides default values varied by exception. * {{{ * val formatDefaulting: Catch[Int] = failAsValue(classOf[NumberFormatException])(0) * val nullDefaulting: Catch[Int] = failAsValue(classOf[NullPointerException])(-1) * val otherDefaulting: Catch[Int] = nonFatalCatch withApply(_ => -100) * * val combinedDefaulting: Catch[Int] = formatDefaulting or nullDefaulting or otherDefaulting * * def p(s: String): Int = s.length * s.toInt * * // Int = 0 * combinedDefaulting(p("tenty-nine")) * * // Int = -1 * combinedDefaulting(p(null: String)) * * // Int = -100 * combinedDefaulting(throw new IllegalStateException) * * // Int = 22 * combinedDefaulting(p("11")) * }}} * * @groupname composition-catch Catch behavior composition * @groupprio composition-catch 10 * @groupdesc composition-catch Build Catch objects from exception lists and catch logic * * @groupname composition-finally Finally behavior composition * @groupprio composition-finally 20 * @groupdesc composition-finally Build Catch objects from finally logic * * @groupname canned-behavior General purpose catch objects * @groupprio canned-behavior 30 * @groupdesc canned-behavior Catch objects with predefined behavior. Use combinator methods to compose additional behavior. * * @groupname dsl DSL behavior composition * @groupprio dsl 40 * @groupdesc dsl Expressive Catch behavior composition * * @groupname composition-catch-promiscuously Promiscuous Catch behaviors * @groupprio composition-catch-promiscuously 50 * @groupdesc composition-catch-promiscuously Useful if catching `ControlThrowable` or `InterruptedException` is required. * * @groupname logic-container Logic Containers * @groupprio logic-container 60 * @groupdesc logic-container Containers for catch and finally behavior. * * @define protectedExceptions `ControlThrowable` or `InterruptedException` * * @author Paul Phillips */ object Exception { type Catcher[+T] = PartialFunction[Throwable, T] def mkCatcher[Ex <: Throwable: ClassTag, T](isDef: Ex => Boolean, f: Ex => T) = new Catcher[T] { private def downcast(x: Throwable): Option[Ex] = if (classTag[Ex].runtimeClass.isAssignableFrom(x.getClass)) Some(x.asInstanceOf[Ex]) else None def isDefinedAt(x: Throwable) = downcast(x) exists isDef def apply(x: Throwable): T = f(downcast(x).get) } def mkThrowableCatcher[T](isDef: Throwable => Boolean, f: Throwable => T) = mkCatcher(isDef, f) implicit def throwableSubtypeToCatcher[Ex <: Throwable: ClassTag, T](pf: PartialFunction[Ex, T]) = mkCatcher(pf.isDefinedAt _, pf.apply _) /** !!! Not at all sure of every factor which goes into this, * and/or whether we need multiple standard variations. * @return true if `x` is $protectedExceptions otherwise false. */ def shouldRethrow(x: Throwable): Boolean = x match { case _: ControlThrowable => true case _: InterruptedException => true // case _: java.lang.Error => true ? case _ => false } trait Described { protected val name: String private var _desc: String = "" def desc = _desc def withDesc(s: String): this.type = { _desc = s this } override def toString() = name + "(" + desc + ")" } /** A container class for finally code. * @group logic-container */ class Finally private[Exception](body: => Unit) extends Described { protected val name = "Finally" def and(other: => Unit): Finally = new Finally({ body ; other }) def invoke() { body } } /** A container class for catch/finally logic. * * Pass a different value for rethrow if you want to probably * unwisely allow catching control exceptions and other throwables * which the rest of the world may expect to get through. * @tparam T result type of bodies used in try and catch blocks * @param pf Partial function used when applying catch logic to determine result value * @param fin Finally logic which if defined will be invoked after catch logic * @param rethrow Predicate on throwables determining when to rethrow a caught [[Throwable]] * @group logic-container */ class Catch[+T]( val pf: Catcher[T], val fin: Option[Finally] = None, val rethrow: Throwable => Boolean = shouldRethrow) extends Described { protected val name = "Catch" /** Create a new Catch with additional exception handling logic. */ def or[U >: T](pf2: Catcher[U]): Catch[U] = new Catch(pf orElse pf2, fin, rethrow) def or[U >: T](other: Catch[U]): Catch[U] = or(other.pf) /** Apply this catch logic to the supplied body. */ def apply[U >: T](body: => U): U = try body catch { case x if rethrow(x) => throw x case x if pf isDefinedAt x => pf(x) } finally fin foreach (_.invoke()) /** Create a new Catch container from this object and the supplied finally body. * @param body The additional logic to apply after all existing finally bodies */ def andFinally(body: => Unit): Catch[T] = { val appendedFin = fin map(_ and body) getOrElse new Finally(body) new Catch(pf, Some(appendedFin), rethrow) } /** Apply this catch logic to the supplied body, mapping the result * into `Option[T]` - `None` if any exception was caught, `Some(T)` otherwise. */ def opt[U >: T](body: => U): Option[U] = toOption(Some(body)) /** Apply this catch logic to the supplied body, mapping the result * into `Either[Throwable, T]` - `Left(exception)` if an exception was caught, * `Right(T)` otherwise. */ def either[U >: T](body: => U): Either[Throwable, U] = toEither(Right(body)) /** Apply this catch logic to the supplied body, mapping the result * into `Try[T]` - `Failure` if an exception was caught, `Success(T)` otherwise. */ def withTry[U >: T](body: => U): scala.util.Try[U] = toTry(Success(body)) /** Create a `Catch` object with the same `isDefinedAt` logic as this one, * but with the supplied `apply` method replacing the current one. */ def withApply[U](f: Throwable => U): Catch[U] = { val pf2 = new Catcher[U] { def isDefinedAt(x: Throwable) = pf isDefinedAt x def apply(x: Throwable) = f(x) } new Catch(pf2, fin, rethrow) } /** Convenience methods. */ def toOption: Catch[Option[T]] = withApply(_ => None) def toEither: Catch[Either[Throwable, T]] = withApply(Left(_)) def toTry: Catch[scala.util.Try[T]] = withApply(x => Failure(x)) } final val nothingCatcher: Catcher[Nothing] = mkThrowableCatcher(_ => false, throw _) final def nonFatalCatcher[T]: Catcher[T] = mkThrowableCatcher({ case NonFatal(_) => true; case _ => false }, throw _) final def allCatcher[T]: Catcher[T] = mkThrowableCatcher(_ => true, throw _) /** The empty `Catch` object. * @group canned-behavior **/ final val noCatch: Catch[Nothing] = new Catch(nothingCatcher) withDesc "<nothing>" /** A `Catch` object which catches everything. * @group canned-behavior **/ final def allCatch[T]: Catch[T] = new Catch(allCatcher[T]) withDesc "<everything>" /** A `Catch` object which catches non-fatal exceptions. * @group canned-behavior **/ final def nonFatalCatch[T]: Catch[T] = new Catch(nonFatalCatcher[T]) withDesc "<non-fatal>" /** Creates a `Catch` object which will catch any of the supplied exceptions. * Since the returned `Catch` object has no specific logic defined and will simply * rethrow the exceptions it catches, you will typically want to call `opt`, * `either` or `withTry` on the return value, or assign custom logic by calling "withApply". * * Note that `Catch` objects automatically rethrow `ControlExceptions` and others * which should only be caught in exceptional circumstances. If you really want * to catch exactly what you specify, use `catchingPromiscuously` instead. * @group composition-catch */ def catching[T](exceptions: Class[_]*): Catch[T] = new Catch(pfFromExceptions(exceptions : _*)) withDesc (exceptions map (_.getName) mkString ", ") def catching[T](c: Catcher[T]): Catch[T] = new Catch(c) /** Creates a `Catch` object which will catch any of the supplied exceptions. * Unlike "catching" which filters out those in shouldRethrow, this one will * catch whatever you ask of it including $protectedExceptions. * @group composition-catch-promiscuously */ def catchingPromiscuously[T](exceptions: Class[_]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions : _*)) def catchingPromiscuously[T](c: Catcher[T]): Catch[T] = new Catch(c, None, _ => false) /** Creates a `Catch` object which catches and ignores any of the supplied exceptions. * @group composition-catch */ def ignoring(exceptions: Class[_]*): Catch[Unit] = catching(exceptions: _*) withApply (_ => ()) /** Creates a `Catch` object which maps all the supplied exceptions to `None`. * @group composition-catch */ def failing[T](exceptions: Class[_]*): Catch[Option[T]] = catching(exceptions: _*) withApply (_ => None) /** Creates a `Catch` object which maps all the supplied exceptions to the given value. * @group composition-catch */ def failAsValue[T](exceptions: Class[_]*)(value: => T): Catch[T] = catching(exceptions: _*) withApply (_ => value) class By[T,R](f: T => R) { def by(x: T): R = f(x) } /** Returns a partially constructed `Catch` object, which you must give * an exception handler function as an argument to `by`. * @example * {{{ * handling(classOf[MalformedURLException], classOf[NullPointerException]) by (_.printStackTrace) * }}} * @group dsl */ // TODO: Add return type def handling[T](exceptions: Class[_]*) = { def fun(f: Throwable => T) = catching(exceptions: _*) withApply f new By[Throwable => T, Catch[T]](fun _) } /** Returns a `Catch` object with no catch logic and the argument as the finally logic. * @group composition-finally */ def ultimately[T](body: => Unit): Catch[T] = noCatch andFinally body /** Creates a `Catch` object which unwraps any of the supplied exceptions. * @group composition-catch */ def unwrapping[T](exceptions: Class[_]*): Catch[T] = { def unwrap(x: Throwable): Throwable = if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause) else x catching(exceptions: _*) withApply (x => throw unwrap(x)) } /** Private **/ private def wouldMatch(x: Throwable, classes: scala.collection.Seq[Class[_]]): Boolean = classes exists (_ isAssignableFrom x.getClass) private def pfFromExceptions(exceptions: Class[_]*): PartialFunction[Throwable, Nothing] = { case x if wouldMatch(x, exceptions) => throw x } }
felixmulder/scala
src/library/scala/util/control/Exception.scala
Scala
bsd-3-clause
14,641
package com.workingtheory.scala import org.apache.logging.log4j.{LogManager, Logger} /** * This class demonstrates 'how to write main method' in Scala and print a hello world. * * Unfortunately, Scala doesn't support class level 'static' variables or methods. * Instead, it has a concept of 'object' to hold all the static variables or methods of a class. * * Thus, if we need 'public static void main' in scala, we create an 'object' instead of a class and * then declare the method 'main' in it. * */ object HelloWorld { private val logger: Logger = LogManager.getLogger(HelloWorld.this) /** * 'def' keyword is used to declare methods. * Since we are inside 'object', method {@link #main(String[]) main} becomes a static one. * * @param args command line arguments, passed on to the program. */ def main(args: Array[String]): Unit = { /** * Scala globally defines many 'java equivalent' useful methods like 'System.out.print' and 'System.out.println'. * * Remember, No need of semicolons at the end of the line. */ print("Hello World .. ") } }
kedar-joshi/baby-steps
hello-scala/src/main/scala/com/workingtheory/scala/HelloWorld.scala
Scala
apache-2.0
1,108
package co.blocke.scalajack package typeadapter import model._ import co.blocke.scala_reflection.impl.Clazzes._ import co.blocke.scala_reflection.info._ import co.blocke.scala_reflection.impl.PrimitiveType import co.blocke.scala_reflection._ import scala.collection.mutable object PermissiveBigDecimalTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[BigDecimal] with ScalarTypeAdapter[BigDecimal]: def matches(concrete: RType): Boolean = concrete match { case u: Scala2Info if u.infoClass.getName == "scala.math.BigDecimal" => true case _ => false } def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[BigDecimal] = this val info = RType.of[scala.math.BigDecimal] def read(parser: Parser): BigDecimal = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(BigDecimalTypeAdapterFactory, emptyStringOk = false) .read(parser) else BigDecimalTypeAdapterFactory.read(parser) def write[WIRE](t: BigDecimal, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = BigDecimalTypeAdapterFactory.write(t, writer, out) object PermissiveBigIntTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[BigInt] with ScalarTypeAdapter[BigInt]: def matches(concrete: RType): Boolean = concrete match { case u: Scala2Info if u.infoClass.getName == "scala.math.BigInt" => true case _ => false } def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[BigInt] = this val info = RType.of[scala.math.BigInt] def read(parser: Parser): BigInt = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(BigIntTypeAdapterFactory, emptyStringOk = false) .read(parser) else BigIntTypeAdapterFactory.read(parser) def write[WIRE](t: BigInt, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = BigIntTypeAdapterFactory.write(t, writer, out) object PermissiveBooleanTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Boolean] with ScalarTypeAdapter[Boolean]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Boolean.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Boolean] = this val info = RType.of[Boolean] def read(parser: Parser): Boolean = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(BooleanTypeAdapterFactory, emptyStringOk = false) .read(parser) else BooleanTypeAdapterFactory.read(parser) def write[WIRE](t: Boolean, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = BooleanTypeAdapterFactory.write(t, writer, out) object PermissiveByteTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Byte] with ScalarTypeAdapter[Byte]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Byte.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Byte] = this val info = RType.of[Byte] def read(parser: Parser): Byte = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(ByteTypeAdapterFactory, emptyStringOk = false) .read(parser) else ByteTypeAdapterFactory.read(parser) def write[WIRE](t: Byte, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = ByteTypeAdapterFactory.write(t, writer, out) object PermissiveDoubleTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Double] with ScalarTypeAdapter[Double]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Double.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Double] = this val info = RType.of[Double] def read(parser: Parser): Double = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(DoubleTypeAdapterFactory, emptyStringOk = false) .read(parser) else DoubleTypeAdapterFactory.read(parser) def write[WIRE](t: Double, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = DoubleTypeAdapterFactory.write(t, writer, out) object PermissiveFloatTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Float] with ScalarTypeAdapter[Float]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Float.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Float] = this val info = RType.of[Float] def read(parser: Parser): Float = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(FloatTypeAdapterFactory, emptyStringOk = false) .read(parser) else FloatTypeAdapterFactory.read(parser) def write[WIRE](t: Float, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = FloatTypeAdapterFactory.write(t, writer, out) object PermissiveIntTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Int] with ScalarTypeAdapter[Int]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Int.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Int] = this val info = RType.of[Int] def read(parser: Parser): Int = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(IntTypeAdapterFactory, emptyStringOk = false) .read(parser) else IntTypeAdapterFactory.read(parser) def write[WIRE](t: Int, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = IntTypeAdapterFactory.write(t, writer, out) object PermissiveLongTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Long] with ScalarTypeAdapter[Long]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Long.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Long] = this val info = RType.of[Long] def read(parser: Parser): Long = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(LongTypeAdapterFactory, emptyStringOk = false) .read(parser) else LongTypeAdapterFactory.read(parser) def write[WIRE](t: Long, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = LongTypeAdapterFactory.write(t, writer, out) object PermissiveShortTypeAdapterFactory extends TypeAdapterFactory with TypeAdapter[Short] with ScalarTypeAdapter[Short]: def matches(concrete: RType): Boolean = concrete.infoClass == PrimitiveType.Scala_Short.infoClass def makeTypeAdapter(concrete: RType)(implicit taCache: TypeAdapterCache): TypeAdapter[Short] = this val info = RType.of[Short] def read(parser: Parser): Short = if (parser.nextIsString) parser.jackFlavor .stringWrapTypeAdapterFactory(ShortTypeAdapterFactory, emptyStringOk = false) .read(parser) else ShortTypeAdapterFactory.read(parser) def write[WIRE](t: Short, writer: Writer[WIRE], out: mutable.Builder[WIRE, WIRE]): Unit = ShortTypeAdapterFactory.write(t, writer, out)
gzoller/ScalaJack
core/src/main/scala/co.blocke.scalajack/typeadapter/PermissiveScalaPrimitives.scala
Scala
mit
7,267
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cogx.platform.opencl import cogx.platform.types.KernelCodeTypes.CogOpenCL import com.jogamp.opencl._ import cogx.platform.types.{VirtualFieldRegister, FieldType, AbstractKernel, Opcode} import cogx.utilities.Stats /** Base for OpenCL kernels (both device and CPU) that provides for the * binding of buffers to the inputs and outputs of those kernels, and for * instantiation of those kernels so they can executed. * * It is assumed that these kernel are to be executed according to a * dependency DAG. The protocol for executing them involves two post-order * traversals of the DAG (post-order since that means no kernel is visited * before all of the kernels feeding it have been visited): * * 1. Traverse the DAG post-order, calling `startComputation` on each kernel. * This will cause the kernel to get the output events from the kernels * feeding it (since it can't start until those events have triggered) and * enqueue a request on the command queue to execute the kernel when all of * the input events have occurred. The enqueueing generates an output event * which other kernels dependent on this can use to gate their execution. * * 2. Wait for all output events at the top of the DAG to complete. * * 3. Traverse the DAG again post-order, calling `resetTrigger`. This releases * all events that were generated during the computation, and checks them * all for errors. This sets things up for computation on the next cycle. * * @param opcode The operation performed by this kernel. * @param in The virtual field registers driving the inputs of this kernel. * @param fieldTypes The types of the results generated by this kernel. * * @author Greg Snider */ private[cogx] abstract class OpenCLAbstractKernel(opcode: Opcode, in: Array[VirtualFieldRegister], fieldTypes: Array[FieldType]) extends AbstractKernel(opcode, in, fieldTypes) { /** The language of the kernel. This should be in a platform-independent * subclass of AbstractKernel named 'DeviceKernel' and there should be no * platform-dependent CPU kernels (e.g. OpenCLCpuKernel), but such is life. */ val kernelCodeType = CogOpenCL /** Alternate constructor for the common case of a single-output kernel */ // def this(opcode: Opcode, in: Array[VirtualFieldRegister], fieldType: FieldType) = // this(opcode, in, Array(fieldType)) /** Input registers read by this kernel during execution. */ protected lazy val inputRegisters = inputs.map(_.register.asInstanceOf[OpenCLFieldRegister]).toArray /** Output registers written by this kernel during execution. */ protected lazy val outputRegisters = outputs.map(_.register.asInstanceOf[OpenCLFieldRegister]).toArray /** The runtime CLKernel used by the device. */ protected var clKernel: CLKernel = null /** The OpenCLDevice for this kernel, providing the gateway to the platform, context and commandqueue. */ private var device: OpenCLDevice = null /** The hardware device. */ protected def clDevice: CLDevice = device.clDevice /** Command queue for this kernel. */ protected def commandQueue: OpenCLParallelCommandQueue = device.commandQueue /** Platform for this kernel. */ private def platform: OpenCLPlatform = device.platform /** Context for this kernel. */ protected def clContext = platform.clContext def waitForEvents(events: Seq[CLEvent]) = device.waitForEvents(events) // Add the output VirtualFieldRegisters fieldTypes.foreach(new VirtualFieldRegister(_, this)) // println("### OpenCLAbstractKernel created: " + this + " output(0) = " + outputs(0)) /** Create a short string for debugging. */ override def toString: String = "OpenCLAbstractKernel(" + opcode.toString + ")" + " => " + fieldTypesString + (if (name == "") name else "'" + name + "'") /** The output FieldTypes as a string */ def fieldTypesString = "(" + fieldTypes.mkString(" , ") + ")" /** The input FieldTypes as a string */ def inputFieldTypesString = "(" + in.map(_.fieldType).mkString(" , ") + ")" /** An event list containing a single event that will be "triggered" (taking * on the state CL_COMPLETE or CL_ERROR) when the kernel finishes execution. * The event can be accessed as done.getEvent(0). It can also be waited on * by calling done.waitForEvents. Note that the event in `done` can change * each cycle, so it should be accessed by done.getEvent(0) whenever you * need it for launching a kernel. */ protected var outputTrigger: CLEventList = null /** Get the event list containing a single event that will be triggered * when kernel execution is complete. * * This event can be waited on by calling CLEventList.waitForEvents. * Note that the events in the event list can be, and usually are, * different on every cycle, so this must be looked up each time before * launching a kernel. * * @return An OpenCL event that will be triggered (CL_COMPLETE) when the * kernel successfully finishes execution; if execution fails, this * will take on the state CL_ERROR. */ def done: CLEventList = outputTrigger /** Accumulator of microsecond kernel execution times, if profiled */ lazy val stats = new Stats(" us") /** Called by OpenCLDevice. Instantiates the kernel for execution on a device * (if it's a GPU kernel) or on the CPU. */ def instantiate(_device: OpenCLDevice, kernel: CLKernel = null) { require(clKernel == null) require(device == null) clKernel = kernel device = _device } /** Called by OpenCLDevice. Release all OpenCL resources for this kernel. * * This only removes pointers to OpenCL resources so the garbage collector * can remove them later. The actual releasing of the resources is done * by OpenCLPlatform. */ private[opencl] def release() { if (clKernel != null) clKernel.release() clKernel = null device = null if (outputTrigger != null) { if (outputTrigger.size == 1) { val event = outputTrigger.getEvent(0) if (event != null) if (!event.isReleased) event.release() } } } /** Reset / initialize the kernel state. */ def reset(): Unit // Note: in a prior approach, all kernels would clock their output registers // during phase0Clock(). Now, this responsibility has shifted to the // RecurrentFieldKernels, so nothing is done here by default. /** Clock the output registers on the kernel. */ private[cogx] def phase0Clock() { } /** Asynchronously start execution of a kernel when all inputs are "done" * (events generated by them have triggered). */ private[cogx] def phase1Clock(): Unit /** Check the result of the computation, making sure it completed correctly, * and initialize resources for next computation cycle. Must be called after * the done event is complete. */ private[cogx] def phase2Clock(): Unit /** Get the input register for input `inputIndex`. */ final def inputRegister(inputIndex: Int): OpenCLFieldRegister = inputRegisters(inputIndex) /** Get the output register for output `outputIndex`. */ final def outputRegister(outputIndex: Int): OpenCLFieldRegister = outputRegisters(outputIndex) /** Print out a verbose description of the kernel for debugging. */ def print() { println("OpenCLAbstractKernel " + id + ":") println(" class: " + getClass.getSimpleName) println(" opcode: " + opcode) println(" fieldType: " + fieldTypes.toString) println(" inputCount: " + inputs.length) println(" outputCount: " + outputs.length) for (i <- 0 until in.length) { println(" input " + i + ": kernel " + inputs(i).source.id) } println("---------------- end kernel " + id) } }
hpe-cct/cct-core
src/main/scala/cogx/platform/opencl/OpenCLAbstractKernel.scala
Scala
apache-2.0
8,546
/* * ____ ____ _____ ____ ___ ____ * | _ \\ | _ \\ | ____| / ___| / _/ / ___| Precog (R) * | |_) | | |_) | | _| | | | | /| | | _ Advanced Analytics Engine for NoSQL Data * | __/ | _ < | |___ | |___ |/ _| | | |_| | Copyright (C) 2010 - 2013 SlamData, Inc. * |_| |_| \\_\\ |_____| \\____| /__/ \\____| All Rights Reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ package com.precog.common package security import service._ import com.precog.common.accounts.{Account, AccountId} import akka.util.Duration import java.util.concurrent.TimeUnit._ import com.weiglewilczek.slf4s.Logging import org.joda.time.DateTime import scalaz.{NonEmptyList => NEL, _} import scalaz.std.option._ import scalaz.std.list._ import scalaz.syntax.id._ import scalaz.syntax.monad._ import scalaz.syntax.traverse._ object APIKeyManager { def newUUID() = java.util.UUID.randomUUID.toString // 128 bit API key def newAPIKey(): String = newUUID().toUpperCase // 384 bit grant ID def newGrantId(): String = (newUUID() + newUUID() + newUUID()).toLowerCase.replace("-","") } trait APIKeyManager[M[+_]] extends Logging { self => implicit def M: Monad[M] def rootGrantId: M[GrantId] def rootAPIKey: M[APIKey] def createGrant(name: Option[String], description: Option[String], issuerKey: APIKey, parentIds: Set[GrantId], perms: Set[Permission], expiration: Option[DateTime]): M[Grant] def createAPIKey(name: Option[String], description: Option[String], issuerKey: APIKey, grants: Set[GrantId]): M[APIKeyRecord] def newStandardAccountGrant(accountId: AccountId, path: Path, name: Option[String] = None, description: Option[String] = None): M[Grant] = for { rk <- rootAPIKey rg <- rootGrantId ng <- createGrant(name, description, rk, Set(rg), Account.newAccountPermissions(accountId, path), None) } yield ng def newStandardAPIKeyRecord(accountId: AccountId, name: Option[String] = None, description: Option[String] = None): M[APIKeyRecord] = { val path = Path("/%s/".format(accountId)) val grantName = name.map(_+"-grant") val grantDescription = name.map(_+" account grant") val grant = newStandardAccountGrant(accountId, path, grantName, grantDescription) for { rk <- rootAPIKey ng <- grant nk <- createAPIKey(name, description, rk, Set(ng.grantId)) } yield nk } def listAPIKeys: M[Seq[APIKeyRecord]] def findAPIKey(apiKey: APIKey): M[Option[APIKeyRecord]] def findAPIKeyChildren(apiKey: APIKey): M[Set[APIKeyRecord]] def findAPIKeyAncestry(apiKey: APIKey): M[List[APIKeyRecord]] = { findAPIKey(apiKey) flatMap { case Some(keyRecord) => if (keyRecord.issuerKey == apiKey) M.point(List(keyRecord)) else findAPIKeyAncestry(keyRecord.issuerKey) map { keyRecord :: _ } case None => M.point(List.empty[APIKeyRecord]) } } def listGrants: M[Seq[Grant]] def findGrant(gid: GrantId): M[Option[Grant]] def findGrantChildren(gid: GrantId): M[Set[Grant]] def listDeletedAPIKeys: M[Seq[APIKeyRecord]] def findDeletedAPIKey(apiKey: APIKey): M[Option[APIKeyRecord]] def listDeletedGrants: M[Seq[Grant]] def findDeletedGrant(gid: GrantId): M[Option[Grant]] def findDeletedGrantChildren(gid: GrantId): M[Set[Grant]] def addGrants(apiKey: APIKey, grants: Set[GrantId]): M[Option[APIKeyRecord]] def removeGrants(apiKey: APIKey, grants: Set[GrantId]): M[Option[APIKeyRecord]] def deleteAPIKey(apiKey: APIKey): M[Option[APIKeyRecord]] def deleteGrant(apiKey: GrantId): M[Set[Grant]] def findValidGrant(grantId: GrantId, at: Option[DateTime] = None): M[Option[Grant]] = findGrant(grantId) flatMap { grantOpt => grantOpt map { (grant: Grant) => if (grant.isExpired(at)) None.point[M] else grant.parentIds.foldLeft(some(grant).point[M]) { case (accM, parentId) => accM flatMap { _ traverse { grant => findValidGrant(parentId, at).map(_ => grant) } } } } getOrElse { None.point[M] } } def validGrants(apiKey: APIKey, at: Option[DateTime] = None): M[Set[Grant]] = { logger.trace("Checking grant validity for apiKey " + apiKey) findAPIKey(apiKey) flatMap { _ map { _.grants.toList.traverse(findValidGrant(_, at)) map { _.flatMap(_.toSet)(collection.breakOut): Set[Grant] } } getOrElse { Set.empty.point[M] } } } def deriveGrant(name: Option[String], description: Option[String], issuerKey: APIKey, perms: Set[Permission], expiration: Option[DateTime] = None): M[Option[Grant]] = { validGrants(issuerKey, expiration).flatMap { grants => if(!Grant.implies(grants, perms, expiration)) none[Grant].point[M] else { val minimized = Grant.coveringGrants(grants, perms, expiration).map(_.grantId) if (minimized.isEmpty) { none[Grant].point[M] } else { createGrant(name, description, issuerKey, minimized, perms, expiration) map { some } } } } } def deriveSingleParentGrant(name: Option[String], description: Option[String], issuerKey: APIKey, parentId: GrantId, perms: Set[Permission], expiration: Option[DateTime] = None): M[Option[Grant]] = { validGrants(issuerKey, expiration).flatMap { validGrants => validGrants.find(_.grantId == parentId) match { case Some(parent) if parent.implies(perms, expiration) => createGrant(name, description, issuerKey, Set(parentId), perms, expiration) map { some } case _ => none[Grant].point[M] } } } def deriveAndAddGrant(name: Option[String], description: Option[String], issuerKey: APIKey, perms: Set[Permission], recipientKey: APIKey, expiration: Option[DateTime] = None): M[Option[Grant]] = { deriveGrant(name, description, issuerKey, perms, expiration) flatMap { case Some(grant) => addGrants(recipientKey, Set(grant.grantId)) map { _ map { _ => grant } } case None => none[Grant].point[M] } } def newAPIKeyWithGrants(name: Option[String], description: Option[String], issuerKey: APIKey, grants: Set[v1.NewGrantRequest]): M[Option[APIKeyRecord]] = { val grantList = grants.toList grantList.traverse(grant => hasCapability(issuerKey, grant.permissions, grant.expirationDate)) flatMap { checks => if (checks.forall(_ == true)) { for { newGrants <- grantList traverse { g => deriveGrant(g.name, g.description, issuerKey, g.permissions, g.expirationDate) } newKey <- createAPIKey(name, description, issuerKey, newGrants.flatMap(_.map(_.grantId))(collection.breakOut)) } yield some(newKey) } else { none[APIKeyRecord].point[M] } } } def hasCapability(apiKey: APIKey, perms: Set[Permission], at: Option[DateTime] = None): M[Boolean] = validGrants(apiKey, at).map(Grant.implies(_, perms, at)) }
precog/platform
common/src/main/scala/com/precog/common/security/APIKeyManager.scala
Scala
agpl-3.0
7,576
/* * Copyright (c) 2014-2015 by its authors. Some rights reserved. * See the project homepage at: http://www.monifu.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package monifu.concurrent.cancelables import monifu.concurrent.atomic.AtomicAny import scala.annotation.tailrec import monifu.concurrent.Cancelable /** * Represents a [[monifu.concurrent.Cancelable]] that can be assigned only * once to another cancelable reference. * * Similar to [[monifu.concurrent.cancelables.MultiAssignmentCancelable]], * except that in case of multi-assignment, it throws a * `java.lang.IllegalStateException`. * * If the assignment happens after this cancelable has been canceled, then on * assignment the reference will get canceled too. * * Useful in case you need a forward reference. */ final class SingleAssignmentCancelable private () extends BooleanCancelable { import State._ def isCanceled: Boolean = state.get match { case IsEmptyCanceled | IsCanceled => true case _ => false } /** * Sets the underlying cancelable reference with `s`. * * In case this `SingleAssignmentCancelable` is already canceled, * then the reference `value` will also be canceled on assignment. * * Throws `IllegalStateException` in case this cancelable has already * been assigned. */ @throws(classOf[IllegalStateException]) @tailrec def update(value: Cancelable): Unit = state.get match { case Empty => if (!state.compareAndSet(Empty, IsNotCanceled(value))) update(value) case IsEmptyCanceled => if (!state.compareAndSet(IsEmptyCanceled, IsCanceled)) update(value) else value.cancel() case IsCanceled | IsNotCanceled(_) => throw new IllegalStateException("Cannot assign to SingleAssignmentCancelable, as it was already assigned once") } @tailrec def cancel(): Boolean = state.get match { case Empty => if (!state.compareAndSet(Empty, IsEmptyCanceled)) cancel() else true case old @ IsNotCanceled(s) => if (!state.compareAndSet(old, IsCanceled)) cancel() else { s.cancel() true } case IsEmptyCanceled | IsCanceled => false } /** * Alias for `update(value)` */ def `:=`(value: Cancelable): Unit = update(value) private[this] val state = AtomicAny(Empty : State) private[this] sealed trait State private[this] object State { case object Empty extends State case class IsNotCanceled(s: Cancelable) extends State case object IsCanceled extends State case object IsEmptyCanceled extends State } } object SingleAssignmentCancelable { def apply(): SingleAssignmentCancelable = new SingleAssignmentCancelable() }
sergius/monifu
core/shared/src/main/scala/monifu/concurrent/cancelables/SingleAssignmentCancelable.scala
Scala
apache-2.0
3,279