scala.collection.immutable.List Scala Examples

The following examples show how to use scala.collection.immutable.List. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: InitiateProfilesTables.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.profiles.slick

import com.dataengi.crm.identities.slick.tables.TablesInitiation
import com.dataengi.crm.profiles.slick.tables.ProfilesTableDescription
import com.google.inject.{Inject, Singleton}
import play.api.Configuration
import play.api.db.slick.DatabaseConfigProvider

import scala.collection.immutable.List
import scala.concurrent.ExecutionContext

@Singleton
class InitiateProfilesTables @Inject()(val configuration: Configuration,
                                       protected val dbConfigProvider: DatabaseConfigProvider,
                                       implicit val executionContext: ExecutionContext)
    extends ProfilesTableDescription
    with TablesInitiation {

  val All = List(Profiles)
  createTables(All)
  printMigrationDDL(All)

} 
Example 2
Source File: IterableDecoratorTest.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala.collection
package decorators

import org.junit.{Assert, Test}

import scala.collection.immutable.{LazyList, List, Map, Range}

class IterableDecoratorTest {

  @Test
  def foldSomeLeft(): Unit = {
      val r = Range(0, 100)
      Assert.assertEquals(0, r.foldSomeLeft(0)((x, y) => None))
      Assert.assertEquals(10, r.foldSomeLeft(0)((x, y) => if (y > 10) None else Some(y)))
      Assert.assertEquals(55, r.foldSomeLeft(0)((x, y) => if (y > 10) None else Some(x + y)))
      Assert.assertEquals(4950, r.foldSomeLeft(0)((x, y) => Some(x + y)))

      Assert.assertEquals(10, List[Int]().foldSomeLeft(10)((x, y) => Some(x + y)))
    }

  @Test
  def lazyFoldLeftIsStackSafe(): Unit = {
    val bigList = List.range(1, 50000)
    def sum(as: Iterable[Int]): Int =
      as.lazyFoldLeft(0)(_ + _)

    Assert.assertEquals(sum(bigList), 1249975000)
  }

  @Test
  def lazyFoldLeftIsLazy(): Unit = {
    val nats = LazyList.from(0)
    def exists[A](as: Iterable[A])(f: A => Boolean): Boolean =
      as.lazyFoldLeft(false)(_ || f(_))
    
    Assert.assertTrue(exists(nats)(_ > 100000))
  }

  @Test def lazyFoldRightIsLazy(): Unit = {
    val xs = LazyList.from(0)
    def chooseOne(x: Int): Either[Int, Int => Int]= if (x < (1 << 16)) Right(identity) else Left(x)

    Assert.assertEquals(1 << 16, xs.lazyFoldRight(0)(chooseOne))
  }

  @Test
  def hasIterableOpsWorksWithStringAndMap(): Unit = {
    val result = "foo".foldSomeLeft(0) { case (_, 'o') => None case (n, _) => Some(n + 1) }
    Assert.assertEquals(1, result)

    val result2 =
      Map(1 -> "foo", 2 -> "bar").foldSomeLeft(0) {
        case (n, (k, _)) => if (k == -1) None else Some(n + 1)
      }
    Assert.assertEquals(2, result2)
  }

  @Test
  def splitByShouldHonorEmptyIterator(): Unit = {
    val split = Vector.empty[Int].splitBy(identity)
    Assert.assertEquals(Vector.empty, split)
  }

  @Test
  def splitByShouldReturnSingleSeqWhenSingleElement(): Unit = {
    val value = Vector("1")
    val split = value.splitBy(identity)
    Assert.assertEquals(Vector(value), split)
  }

  @Test
  def splitByShouldReturnSingleSeqWhenAllElHaveTheSameKey(): Unit = {
    val value = Vector("1", "1", "1")
    val split = value.splitBy(identity)
    Assert.assertEquals(Vector(value), split)
  }

  @Test
  def splitByShouldReturnVectorOfVectorOrConsecutiveElementsWithTheSameKey(): Unit = {
    val value = Vector("1", "2", "2", "3", "3", "3", "2", "2")
    val split: Vector[Vector[String]] = value.splitBy(identity)
    Assert.assertEquals(Vector(Vector("1"), Vector("2", "2"), Vector("3", "3", "3"), Vector("2", "2")), split)
  }

  @Test
  def splitByShouldReturnListOfListOfConsecutiveElementsWithTheSameKey(): Unit = {
    val value = List("1", "2", "2", "3", "3", "3", "2", "2")
    val split: List[List[String]] = value.splitBy(identity)
    Assert.assertEquals(List(List("1"), List("2", "2"), List("3", "3", "3"), List("2", "2")), split)
  }

  @Test
  def splitByShouldReturnSetOfSetOfConsecutiveElementsWithTheSameKey(): Unit = {
    val value = Set("1", "2", "2", "3", "3", "3", "2", "2")
    val split: Set[Set[String]] = value.splitBy(identity)
    Assert.assertEquals(Set(Set("1"), Set("2"), Set("3")), split)
  }
} 
Example 3
Source File: MultiSetTest.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala.collection

import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import scala.collection.immutable.List
import org.junit.{Assert, Test}

@RunWith(classOf[JUnit4])
class MultiSetTest {

  @Test
  def equality(): Unit = {
    val ms1 = MultiSet("a", "b", "b", "c")
    val ms2 = MultiSet("a", "b", "b", "c")

    Assert.assertEquals(ms2, ms1)
    Assert.assertEquals(ms1, ms2)
    Assert.assertEquals(ms1.##, ms2.##)
  }

  @Test
  def concat(): Unit = {
    Assert.assertEquals(
      MultiSet(1, 1),
      MultiSet(1).concat(MultiSet(1))
    )
    Assert.assertEquals(
      MultiSet("a", "a", "a"),
      MultiSet("a").concatOccurrences(List(("a", 2)))
    )
  }

  @Test
  def map(): Unit = {
    Assert.assertEquals(
      MultiSet("A", "B", "B"),
      MultiSet("a", "b", "b").map(_.toUpperCase)
    )
    Assert.assertEquals(
      MultiSet(1, 1),
      MultiSet("a", "b").map(_ => 1)
    )
    Assert.assertEquals(
      MultiSet("c", "c", "c", "c"),
      MultiSet("a", "b", "b").mapOccurrences { _ => ("c", 2) }
    )
  }

  @Test
  def testToString(): Unit = {

    def run(ms: MultiSet[Int]): Unit = {
      val actual = ms.toString
      assert(actual.startsWith("MultiSet("), s"`$actual` does not start with `MultiSet(`")
      assert(actual.endsWith(")"), s"`$actual` does not end with `)`")

      // The order of elements in the multiset are not defined, so this test should be robust to order changes
      Assert.assertEquals(ms,
        actual
          .stripPrefix("MultiSet(")
          .stripSuffix(")")
          .split(",")
          .iterator
          .flatMap (_.trim match {
            case "" => None
            case s => Some(s.toInt)
          })
          .to(MultiSet))
    }

    def runForFactory(factory: IterableFactory[MultiSet]): Unit = {
      Assert.assertEquals(factory().toString, "MultiSet()")
      Assert.assertEquals(factory(1).toString, "MultiSet(1)")

      run(factory())
      run(factory(1))
      run(factory(1234))
      run(factory(1,2,3))
      run(factory(1,1,1,2,3))
      run(factory(1,1,1,2,2,2,2,3))
    }

    runForFactory(MultiSet)
    runForFactory(mutable.MultiSet)
    runForFactory(immutable.MultiSet)
  }

} 
Example 4
Source File: ColumnarAggregateExpression.scala    From OAP   with Apache License 2.0 5 votes vote down vote up
package com.intel.sparkColumnarPlugin.expression

import scala.collection.immutable.List
import scala.collection.JavaConverters._
import org.apache.arrow.gandiva.expression._
import org.apache.arrow.vector.types.pojo.ArrowType
import org.apache.arrow.vector.types.pojo.Field

import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.types._

trait ColumnarAggregateExpressionBase extends ColumnarExpression with Logging {
  def requiredColNum: Int
  def expectedResColNum: Int
  def setInputFields(fieldList: List[Field]): Unit = {}
  def doColumnarCodeGen_ext(args: Object): TreeNode = {
    throw new UnsupportedOperationException(s"ColumnarAggregateExpressionBase doColumnarCodeGen_ext is a abstract function.")
  }
}

class ColumnarUniqueAggregateExpression(aggrFieldList: List[Field]) extends ColumnarAggregateExpressionBase with Logging {

  override def requiredColNum: Int = 1
  override def expectedResColNum: Int = 1
  override def doColumnarCodeGen_ext(args: Object): TreeNode = {
    val (keyFieldList, inputFieldList, resultType, resultField) =
      args.asInstanceOf[(List[Field], List[Field], ArrowType, Field)]
    val funcName = "action_unique"
    val inputNode = {
      // if keyList has keys, we need to do groupby by these keys.
      var inputFieldNode = 
        keyFieldList.map({field => TreeBuilder.makeField(field)}).asJava
      val encodeNode = TreeBuilder.makeFunction(
        "encodeArray",
        inputFieldNode,
        resultType)
      val inputAggrFieldNode = 
        List(groupByFuncNode) ::: aggrFieldList.map(field => TreeBuilder.makeField(field))
      val aggregateFuncName = "action_" + funcName
      logInfo(s"${aggregateFuncName}(${inputAggrFieldNode})")
      TreeBuilder.makeFunction(
        aggregateFuncName,
        inputAggrFieldNode.asJava,
        resultType)
    } else {
      val inputFieldNode = 
        aggrFieldList.map(field => TreeBuilder.makeField(field))
      logInfo(s"${funcName}(${inputFieldNode})")
      TreeBuilder.makeFunction(
        funcName,
        inputFieldNode.asJava,
        resultType)
    }
  }
} 
Example 5
Source File: EuExitLinksSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.jsoup.Jsoup
import org.scalatest.{Matchers, WordSpec}
import play.api.i18n.Lang
import play.api.i18n.Messages.Implicits._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.Helpers.{contentAsString, defaultAwaitTimeout}
import java.util.{List => JavaList}
import uk.gov.hmrc.play.views.html.layouts.eu_exit_links

import scala.collection.JavaConverters._
import scala.collection.immutable.List

class EuExitLinksSpec extends WordSpec with Matchers {

  val englishLinkTextEntries: JavaList[String] = List(
    "Prepare your business for the UK leaving the EU",
    "Prepare for EU Exit if you live in the UK",
    "Living in Europe after the UK leaves the EU",
    "Continue to live in the UK after it leaves the EU"
  ).asJava

  val welshLinkTextEntries: JavaList[String] = List(
    "Paratoi eich busnes ar gyfer y DU yn gadael yr UE (Saesneg yn unig)",
    "Paratoi ar gyfer Ymadael â’r UE os ydych yn byw yn y DU (Saesneg yn unig)",
    "Byw yn Ewrop ar ôl i’r DU adael yr UE (Saesneg yn unig)",
    "Parhau i fyw yn y DU ar ôl iddi adael yr UE (Saesneg yn unig)"
  ).asJava

  implicit val application =
    new GuiceApplicationBuilder()
      .configure(Map("play.i18n.langs" -> List("en", "cy")))
      .build()

  "Eu Exit Links on an English Language Page" should {
    implicit val lang = Lang("en")
    val markup        = contentAsString(eu_exit_links())
    val document      = Jsoup.parse(markup)
    val links         = document.getElementsByTag("a")

    "Include the section header" in {
      markup should include("<h2 class=\"heading-medium\">Prepare for EU Exit</h2>")
    }
    "Include four links" in {
      links.size should be(4)
    }
    "Have the correct link text in English" in {
      links.eachText() should be(englishLinkTextEntries)
    }
  }

  "Eu Exit Links on a Welsh Language Page" should {
    implicit val lang = Lang("cy")
    val markup        = contentAsString(eu_exit_links())
    val document      = Jsoup.parse(markup)
    val links         = document.getElementsByTag("a")

    "Include the section header" in {
      markup should include("<h2 class=\"heading-medium\">Paratoi ar gyfer Ymadael â’r UE (Saesneg yn unig)</h2>")
    }
    "Include four links" in {
      links.size should be(4)
    }
    "Have the correct link text in Welsh" in {
      links.eachText() should be(welshLinkTextEntries)
    }
  }
} 
Example 6
Source File: FooterLinksSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.jsoup.Jsoup
import org.scalatest.{Matchers, WordSpec}
import play.api.i18n.Lang
import play.api.test.Helpers._
import play.twirl.api.Html
import uk.gov.hmrc.play.views.html.layouts.FooterLinks
import play.api.i18n.Messages.Implicits._
import play.api.inject.guice.GuiceApplicationBuilder
import java.util.{List => JavaList}
import scala.collection.JavaConverters._
import scala.collection.immutable.List


class FooterLinksSpec extends WordSpec with Matchers {

  implicit val application =
    new GuiceApplicationBuilder()
      .configure(Map("play.i18n.langs" -> List("en", "cy")))
      .build()

  val englishLinkTextEntries: JavaList[String] = List(
    "Cookies",
    "Privacy policy",
    "Terms and conditions",
    "Help using GOV.UK"
  ).asJava

  val welshLinkTextEntries: JavaList[String] = List(
    "Cwcis",
    "Polisi preifatrwydd",
    "Telerau ac Amodau",
    "Help wrth ddefnyddio GOV.UK"
  ).asJava

  "The footerLinks in English" should {

    val footerLinks = new FooterLinks()

    implicit val lang = Lang("en")
    val content  = contentAsString(footerLinks())
    val document = Jsoup.parse(content)
    val links    = document.getElementsByTag("a")

    "include visually hidden h2 text in English" in {
      implicit val lang = Lang("en")
      val content  = contentAsString(footerLinks())
      content should include("<h2 class=\"visually-hidden\">Support links</h2>")
    }

    "Have the correct link text in English" in {
      links.eachText() should be(englishLinkTextEntries)
    }

  }

  "The footerLinks in Welsh" should {

    val footerLinks = new FooterLinks()

    implicit val lang = Lang("cy")
    val content  = contentAsString(footerLinks())
    val document = Jsoup.parse(content)
    val links    = document.getElementsByTag("a")


    "include visually hidden h2 text in Welsh" in {
      content should include("<h2 class=\"visually-hidden\">Cysylltiadau cymorth</h2>")
    }

    "Have the correct link text in Welsh" in {
      links.eachText() should be(welshLinkTextEntries)
    }

  }
} 
Example 7
Source File: ContextMenuUtils.scala    From eclair   with Apache License 2.0 5 votes vote down vote up
package fr.acinq.eclair.gui.utils

import javafx.event.{ActionEvent, EventHandler}
import javafx.scene.control.{ContextMenu, MenuItem}
import javafx.scene.input.{Clipboard, ClipboardContent}

import scala.collection.immutable.List


  def buildCopyContext(actions: List[CopyAction]): ContextMenu = {
    val context = new ContextMenu()
    for (action <- actions) {
      context.getItems.addAll(buildCopyMenuItem(action))
    }
    context
  }

  def buildCopyMenuItem(action: CopyAction): MenuItem = {
    val copyItem = new MenuItem(action.label)
    copyItem.setOnAction(new EventHandler[ActionEvent] {
      override def handle(event: ActionEvent): Unit = copyToClipboard(action.value)
    })
    copyItem
  }

  def copyToClipboard(value: String) = {
    val clipContent = new ClipboardContent
    clipContent.putString(value)
    clip.setContent(clipContent)
  }
} 
Example 8
Source File: SyntaxSpec.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.syntax

import scala.collection.immutable.{ List, Map }

import com.typesafe.config.ConfigFactory
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.error.ConfigReaderException
import pureconfig.generic.auto._

class SyntaxSpec extends AnyFlatSpec with Matchers {

  behavior of "pureconfig.syntax._"

  it should "be able to serialize a ConfigValue from a type with ConfigConvert using the toConfig method" in {
    Map("a" -> 1, "b" -> 2).toConfig shouldBe ConfigFactory.parseString("""{ "a": 1, "b": 2 }""").root()
  }

  it should "be able to load a ConfigValue to a type with ConfigConvert using the to method" in {
    val conf = ConfigFactory.parseString("""{ "a": [1, 2, 3, 4], "b": { "k1": "v1", "k2": "v2" } }""")
    conf.getList("a").to[List[Int]] shouldBe Right(List(1, 2, 3, 4))
    conf.getObject("b").to[Map[String, String]] shouldBe Right(Map("k1" -> "v1", "k2" -> "v2"))
  }

  it should "be able to load a Config to a type with ConfigConvert using the to method" in {
    val conf = ConfigFactory.parseString("""{ "a": [1, 2, 3, 4], "b": { "k1": "v1", "k2": "v2" } }""")
    case class Conf(a: List[Int], b: Map[String, String])
    conf.to[Conf] shouldBe Right(Conf(List(1, 2, 3, 4), Map("k1" -> "v1", "k2" -> "v2")))
  }

  // TODO this shouldn't be here
  it should "fail when trying to convert to basic types from an empty string" in {
    val conf = ConfigFactory.parseString("""{ v: "" }""")
    conf.getValue("v").to[Boolean].isLeft shouldBe true
    conf.getValue("v").to[Double].isLeft shouldBe true
    conf.getValue("v").to[Float].isLeft shouldBe true
    conf.getValue("v").to[Int].isLeft shouldBe true
    conf.getValue("v").to[Long].isLeft shouldBe true
    conf.getValue("v").to[Short].isLeft shouldBe true
  }

  it should "fail with Exception when trying to convert to basic types from an empty string" in {
    val conf = ConfigFactory.parseString("""{ v: "" }""")

    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Boolean]
    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Double]
    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Float]
    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Int]
    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Long]
    a[ConfigReaderException[_]] should be thrownBy conf.getValue("v").toOrThrow[Short]
  }

  it should "pass when trying to convert to basic types with pureconfig.syntax toOrThrow" in {
    val conf = ConfigFactory.parseString("""{ b: true, d: 2.2, f: 3.3, i: 2, l: 2, s: 2, cs: "Cheese"}""")

    conf.getValue("b").toOrThrow[Boolean] shouldBe true
    conf.getValue("d").toOrThrow[Double] shouldBe 2.2
    conf.getValue("f").toOrThrow[Float] shouldBe 3.3f
    conf.getValue("i").toOrThrow[Int] shouldBe 2
    conf.getValue("l").toOrThrow[Long] shouldBe 2L
    conf.getValue("s").toOrThrow[Short] shouldBe 2.toShort
    conf.getValue("cs").toOrThrow[String] shouldBe "Cheese"

  }
} 
Example 9
Source File: DefaultJdbcSchemaReader.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.codegen.jdbc.gen

import java.sql.{ Connection, ResultSet }

import io.getquill.codegen.jdbc.DatabaseTypes.{ DatabaseType, Oracle }
import io.getquill.codegen.jdbc.model.JdbcTypes.{ JdbcConnectionMaker, JdbcSchemaReader }
import io.getquill.codegen.model.{ JdbcColumnMeta, JdbcTableMeta, RawSchema }
import io.getquill.codegen.util.StringUtil._
import io.getquill.util.Using
import scala.util.{ Success, Failure }

import scala.annotation.tailrec
import scala.collection.immutable.List

class DefaultJdbcSchemaReader(
  databaseType: DatabaseType
) extends JdbcSchemaReader {

  @tailrec
  private def resultSetExtractor[T](rs: ResultSet, extractor: (ResultSet) => T, acc: List[T] = List()): List[T] = {
    if (!rs.next())
      acc.reverse
    else
      resultSetExtractor(rs, extractor, extractor(rs) :: acc)
  }

  private[getquill] def schemaPattern(schema: String) =
    databaseType match {
      case Oracle => schema // Oracle meta fetch takes minutes to hours if schema is not specified
      case _      => null
    }

  def jdbcEntityFilter(ts: JdbcTableMeta) =
    ts.tableType.existsInSetNocase("table", "view", "user table", "user view", "base table")

  private[getquill] def extractTables(connectionMaker: () => Connection): List[JdbcTableMeta] = {
    val output = Using.Manager { use =>
      val conn = use(connectionMaker())
      val schema = conn.getSchema
      val rs = use {
        conn.getMetaData.getTables(
          null,
          schemaPattern(schema),
          null,
          null
        )
      }
      resultSetExtractor(rs, rs => JdbcTableMeta.fromResultSet(rs))
    }
    val unfilteredJdbcEntities =
      output match {
        case Success(value) => value
        case Failure(e)     => throw e
      }

    unfilteredJdbcEntities.filter(jdbcEntityFilter(_))
  }

  private[getquill] def extractColumns(connectionMaker: () => Connection): List[JdbcColumnMeta] = {
    val output = Using.Manager { use =>
      val conn = use(connectionMaker())
      val schema = conn.getSchema
      val rs = use {
        conn.getMetaData.getColumns(
          null,
          schemaPattern(schema),
          null,
          null
        )
      }
      resultSetExtractor(rs, rs => JdbcColumnMeta.fromResultSet(rs))
    }
    output match {
      case Success(value) => value
      case Failure(e)     => throw e
    }
  }

  override def apply(connectionMaker: JdbcConnectionMaker): Seq[RawSchema[JdbcTableMeta, JdbcColumnMeta]] = {
    val tableMap =
      extractTables(connectionMaker)
        .map(t => ((t.tableCat, t.tableSchem, t.tableName), t))
        .toMap

    val columns = extractColumns(connectionMaker)
    val tableColumns =
      columns
        .groupBy(c => (c.tableCat, c.tableSchem, c.tableName))
        .map({ case (tup, cols) => tableMap.get(tup).map(RawSchema(_, cols)) })
        .collect({ case Some(tbl) => tbl })

    tableColumns.toSeq
  }
} 
Example 10
Source File: ContextMarker.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.logging
package impl

import java.util

import org.slf4j.Marker

import scala.collection.immutable.{List, Seq}

final case class ContextMarker(ctx: LoggedValue, referenceList: Seq[Marker] = List.empty) extends Marker {
  import scala.jdk.CollectionConverters._

  override def getName: String                    = "Context"
  override def add(reference: Marker): Unit = {}
  override def remove(reference: Marker): Boolean = false
  override def hasChildren: Boolean               = referenceList.nonEmpty
  override def hasReferences: Boolean             = referenceList.nonEmpty
  override def iterator(): util.Iterator[Marker]  = referenceList.iterator.asJava
  override def contains(other: Marker): Boolean   = referenceList.contains(other)
  override def contains(name: String): Boolean    = referenceList.map(_.getName).contains(name)

  def +(marker: Marker)         = copy(ctx, marker +: referenceList)
  def addMarker(marker: Marker) = this + marker
} 
Example 11
Source File: DerivingConfig.scala    From scalaz-deriving   with GNU Lesser General Public License v3.0 5 votes vote down vote up
// Copyright: 2017 - 2020 Sam Halliday
// License: http://www.gnu.org/licenses/lgpl-3.0.en.html

package scalaz.macros

import java.net.URL

import scala.Predef.{ wrapRefArray, ArrowAssoc }
import scala.collection.immutable.{ List, Map }
import scala.collection.JavaConverters._

private[scalaz] final case class DerivingConfig(targets: Map[String, String])
private[scalaz] object DerivingConfig {
  private type Result[T] = Either[String, T]
  private type Stringy   = Map[String, String]

  // cached to avoid hitting disk on every use of the macro.
  private[scalaz] lazy val targets: Result[Stringy] =
    getClass.getClassLoader
      .getResources("deriving.conf")
      .asScala
      .toList
      .map { res =>
        for {
          s <- readResource(res)
          c <- parseProperties(s)
        } yield c
      }
      .reverse // map addition means the last element wins
      .fold(EmptyResults) {
        // it's almost like we have a Monoid! Except, no, it's stdlib
        case (Right(m1), Right(m2)) => Right(m1 ++ m2)
        case (Left(e1), _)          => Left(e1)
        case (_, Left(e2))          => Left(e2)
      }
  private[this] val EmptyResults: Result[Stringy]   = Right(Map.empty)

  private[this] def parseProperties(config: String): Result[Stringy] =
    try Right(
      config
        .split("\n")
        .toList
        .filterNot(_.isEmpty)
        .filterNot(_.startsWith("#"))
        .map(_.split("=").toList)
        .map {
          case List(from, to) => from.trim -> to.trim
          case other          =>
            // I'd have used Left with traverse, but this is stdlib...
            throw new IllegalArgumentException(
              s"expected 2 parts but got ${other.size} in $other"
            )
        }
        .toMap
    )
    catch {
      case t: Throwable =>
        Left(t.getMessage)
    }

  private[this] def readResource(resUrl: URL): Either[String, String] =
    readInputStream(resUrl.openStream())

  private[this] def readInputStream(
    is: java.io.InputStream
  ): Either[String, String] =
    try {
      val baos     = new java.io.ByteArrayOutputStream()
      val data     = Array.ofDim[Byte](2048)
      var len: Int = 0
      def read(): Int = { len = is.read(data); len }
      while (read != -1)
        baos.write(data, 0, len)
      Right(baos.toString("UTF-8"))
    } catch {
      case t: Throwable => Left(t.getMessage)
    } finally is.close()

} 
Example 12
Source File: ArgParse.scala    From xml-avro   with Apache License 2.0 5 votes vote down vote up
package in.dreamlabs.xmlavro.config

import javax.xml.namespace.QName

import scala.collection.immutable.List
import scala.collection.mutable
import scala.reflect.io.Path
import scala.reflect.runtime.universe._


class ArgParse(args: Seq[String]) {
  private val argsMap = {
    val map = mutable.Map[String, List[String]]()
    val len = args.length
    var i = 0
    while (i < len) {
      val arg = args(i)
      if (arg.startsWith("--") || (arg.startsWith("-") && arg.length == 2)) {
        val name = arg stripPrefix "-" stripPrefix "-"
        val values = mutable.ListBuffer[String]()
        while (i + 1 < len && !args(i + 1).startsWith("-")) {
          i += 1
          values += args(i)
        }
        map += (name -> values.toList)
      }
      i += 1
    }
    map
  }


  def opt[T: TypeTag](name: String, short: Char): Option[T] = {
    if (argsMap.contains(name) || argsMap.contains(short + "")) {
      val key = if (argsMap contains name) name else short + ""
      val values = argsMap(key)
      try
        Some(value[T](values))
      catch {
        case e: IllegalArgumentException => throw new IllegalArgumentException(s"${e.getMessage} for $key", e)
      }
    } else None
  }

  private def value[T: TypeTag](original: List[String]): T = {
    typeOf[T] match {
      case t if t =:= typeOf[String] => original.fetch().asInstanceOf[T]
      case t if t =:= typeOf[Int] => original.fetch().toInt.asInstanceOf[T]
      case t if t =:= typeOf[Double] => original.fetch().toDouble.asInstanceOf[T]
      case t if t =:= typeOf[Boolean] => original.fetch().toBoolean.asInstanceOf[T]
      case t if t =:= typeOf[Path] => Path(original.fetch()).asInstanceOf[T]
      case t if t =:= typeOf[List[String]] => original.validate().asInstanceOf[T]
      case t if t =:= typeOf[List[Int]] => original.validate().map(value => value.toInt).asInstanceOf[T]
      case t if t =:= typeOf[List[Double]] => original.validate().map(value => value.toDouble).asInstanceOf[T]
      case t if t =:= typeOf[List[Boolean]] => original.validate().map(value => value.toBoolean).asInstanceOf[T]
      case t if t =:= typeOf[List[Path]] => original.validate().map(value => Path(value)).asInstanceOf[T]
      case t if t =:= typeOf[QName] => QName.valueOf(original.fetch()).asInstanceOf[T]
      case other => throw new IllegalArgumentException(s"Type $other is not yet supported")
    }
  }
  def toggle(name: String, short: Char): Option[Boolean] = {
    if (argsMap.contains(name) || argsMap.contains(short + "")) {
      val key = if (argsMap contains name) name else short + ""
      val values = argsMap(key)
      if (values.nonEmpty)
        throw new IllegalArgumentException(s"Too many values provided for $key")
      else
        Some(true)
    } else None
  }

  implicit class MyList[String](list: List[String]) {
    def fetch(): String = {
      if (list.length > 1)
        throw new IllegalArgumentException(s"Too many values provided")
      else if (list.isEmpty)
        throw new IllegalArgumentException(s"Too less values provided")
      else list.head
    }

    def validate(): List[String] = {
      if (list.isEmpty)
        throw new IllegalArgumentException(s"Too less values provided")
      else list
    }
  }

}