scala.util.Failure Scala Examples
The following examples show how to use scala.util.Failure.
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: DateTimeTools.scala From pertax-frontend with Apache License 2.0 | 9 votes |
package util import com.google.inject.{Inject, Singleton} import org.joda.time.format.{DateTimeFormat, DateTimeFormatter} import org.joda.time.{DateTime, _} import play.api.Logger import uk.gov.hmrc.time.CurrentTaxYear import scala.util.{Failure, Success, Try} import java.time.{LocalDateTime => JavaLDT} object DateTimeTools extends CurrentTaxYear { //Timezone causing problem on dev server val defaultTZ = DateTimeZone.forID("Europe/London") val unixDateFormat = "yyyy-MM-dd" val unixDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss" val humanDateFormat = "dd MMMMM yyyy" //Returns for example 1516 in March 2016 def previousAndCurrentTaxYear = previousAndCurrentTaxYearFromGivenYear(current.currentYear) def previousAndCurrentTaxYearFromGivenYear(year: Int) = { def y = year (y - 1).toString.takeRight(2) + (y).toString.takeRight(2) } private def formatter(pattern: String): DateTimeFormatter = DateTimeFormat.forPattern(pattern).withZone(defaultTZ) def short(dateTime: LocalDate) = formatter("dd/MM/yyy").print(dateTime) def asHumanDateFromUnixDate(unixDate: String): String = Try(DateTimeFormat.forPattern(humanDateFormat).print(DateTime.parse(unixDate))) match { case Success(v) => v case Failure(e) => { Logger.warn("Invalid date parse in DateTimeTools.asHumanDateFromUnixDate: " + e) unixDate } } def toPaymentDate(dateTime: JavaLDT): LocalDate = new LocalDate(dateTime.getYear, dateTime.getMonthValue, dateTime.getDayOfMonth) override def now: () => DateTime = DateTime.now } @Singleton class DateTimeTools @Inject()() { def showSendTaxReturnByPost = { val start = new DateTime(s"${DateTime.now().getYear}-11-01T00:00:00Z") val end = new DateTime(s"${DateTime.now().getYear + 1}-01-31T23:59:59Z") !DateTime.now().isAfter(start) && DateTime.now().isBefore(end) } }
Example 2
Source File: AbstractWebServer.scala From ohara with Apache License 2.0 | 6 votes |
package oharastream.ohara.shabondi.common import akka.Done import akka.actor.ActorSystem import akka.event.Logging import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.server.{Directives, Route} import akka.http.scaladsl.settings.ServerSettings import oharastream.ohara.common.util.Releasable import scala.concurrent._ import scala.concurrent.duration.Duration import scala.io.StdIn import scala.util.{Failure, Success} private[shabondi] abstract class AbstractWebServer extends Directives with Releasable { implicit protected val actorSystem: ActorSystem = ActorSystem(Logging.simpleName(this).replaceAll("\\$", "")) protected def routes: Route protected def postBinding(binding: ServerBinding): Unit = { val hostname = binding.localAddress.getHostName val port = binding.localAddress.getPort actorSystem.log.info(s"Server online at http://$hostname:$port/") } protected def postBindingFailure(cause: Throwable): Unit = { actorSystem.log.error(cause, s"Error starting the server ${cause.getMessage}") } protected def waitForShutdownSignal()(implicit ec: ExecutionContext): Future[Done] = { val promise = Promise[Done]() sys.addShutdownHook { promise.trySuccess(Done) } Future { blocking { if (StdIn.readLine("Press <RETURN> to stop Shabondi WebServer...\n") != null) promise.trySuccess(Done) } } promise.future } protected def postServerShutdown(): Unit = actorSystem.log.info("Shutting down the server") def start(bindInterface: String, port: Int): Unit = { start(bindInterface, port, ServerSettings(actorSystem)) } def start(bindInterface: String, port: Int, settings: ServerSettings): Unit = { implicit val executionContext: ExecutionContextExecutor = actorSystem.dispatcher val bindingFuture: Future[Http.ServerBinding] = Http().bindAndHandle( handler = routes, interface = bindInterface, port = port, settings = settings ) bindingFuture.onComplete { case Success(binding) => postBinding(binding) case Failure(cause) => postBindingFailure(cause) } Await.ready( bindingFuture.flatMap(_ => waitForShutdownSignal()), Duration.Inf ) bindingFuture .flatMap(_.unbind()) .onComplete { _ => postServerShutdown() actorSystem.terminate() } } override def close(): Unit = actorSystem.terminate() }
Example 3
Source File: ComponentsFixture.scala From daml with Apache License 2.0 | 6 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.navigator.test import java.util.concurrent.atomic.AtomicReference import com.daml.navigator.test.config.Arguments import com.daml.navigator.test.runner.{HeadNavigator, PackagedDamlc, PackagedSandbox} import com.typesafe.scalalogging.LazyLogging import scala.io.Source import scala.util.{Failure, Success, Try} class ComponentsFixture( val args: Arguments, val navigatorPort: Int, val sandboxPort: Int, val scenario: String ) extends LazyLogging { // A list of commands on how to destroy started processes private val killProcs: AtomicReference[List[Unit => Unit]] = new AtomicReference(List.empty) private val onlineUrl = s"http://localhost:$navigatorPort/api/about" private def get( url: String, connectTimeout: Int = 1000, readTimeout: Int = 1000, requestMethod: String = "GET" ): String = { import java.net.{URL, HttpURLConnection} val connection = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection] connection.setConnectTimeout(connectTimeout) connection.setReadTimeout(readTimeout) connection.setRequestMethod(requestMethod) val inputStream = connection.getInputStream val content = Source.fromInputStream(inputStream).mkString if (inputStream != null) inputStream.close() content } def startup(): Try[Unit] = { if (args.startComponents) { logger.info("Starting the sandbox and the Navigator") for { (darFile, tempFiles) <- Try(PackagedDamlc.run(args.damlPath)) sandbox <- Try(PackagedSandbox.runAsync(sandboxPort, darFile, scenario)) _ = killProcs.updateAndGet(s => sandbox :: s) navigator <- Try( HeadNavigator.runAsync(args.navConfPAth, args.navigatorDir, navigatorPort, sandboxPort)) _ = killProcs.updateAndGet(s => navigator :: s) } yield { () } } else { Success(()) } } private def retry[R](action: => R, maxRetries: Int, delayMillis: Int): Try[R] = { def retry0(count: Int): Try[R] = { Try(action) match { case Success(r) => Success(r) case Failure(e) => if (count > maxRetries) { logger.error( s"Navigator is not available after $maxRetries retries with $delayMillis millis interval.") Failure(e) } else { logger.info(s"Navigator is not available yet, waiting $delayMillis millis ") Thread.sleep(delayMillis.toLong) retry0(count + 1) } } } retry0(0) } def waitForNavigator(): Try[Unit] = { logger.info(s"Waiting for the Navigator to start up (waiting for $onlineUrl)") retry({ get(onlineUrl); () }, 120, 1000) } def shutdown(): Unit = { killProcs.getAndUpdate(procs => { procs.foreach(killAction => Try { killAction(()) }) List.empty }) () } }
Example 4
Source File: AsyncUdashSharedTest.scala From udash-core with Apache License 2.0 | 6 votes |
package io.udash.testing import org.scalactic.source.Position import org.scalajs.dom import org.scalatest.{Assertion, Succeeded} import scala.concurrent.{ExecutionContext, Future, Promise} import scala.scalajs.concurrent.JSExecutionContext import scala.scalajs.js.Date import scala.util.{Failure, Success} trait AsyncUdashSharedTest extends AsyncUdashSharedTestBase { override implicit def executionContext: ExecutionContext = JSExecutionContext.queue override def retrying(code: => Any)(implicit patienceConfig: PatienceConfig, pos: Position): Future[Assertion] = { val start = Date.now() val p = Promise[Assertion] var lastEx: Option[Throwable] = None def startTest(): Unit = { dom.window.setTimeout(() => { if (patienceConfig.timeout.toMillis > Date.now() - start) { try { code p.complete(Success(Succeeded)) } catch { case ex: Throwable => lastEx = Some(ex) startTest() } } else { p.complete(Failure(lastEx.getOrElse(RetryingTimeout()))) } }, patienceConfig.interval.toMillis.toDouble) } startTest() p.future } }
Example 5
Source File: BasicCurrencyConversion.scala From HANAVora-Extensions with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.currency.basic import org.apache.spark.sql.currency.ConversionRateNotFoundException import org.apache.spark.sql.currency.basic.BasicCurrencyConversion.RatesMap import scala.util.{Failure, Success, Try} object BasicCurrencyConversion { type CurrencyKey = (String, String) type DateKey = Int type RatesMap = DualKeyPartialSortedMap[CurrencyKey, DateKey, java.math.BigDecimal] } def convert(amount: java.math.BigDecimal, from: String, to: String, date: String): Try[Option[java.math.BigDecimal]] = { val dateKey = date.replaceAll("-", "").toInt val currencyKey = (from, to) val converted = rates.getSortedKeyFloorValue(currencyKey, dateKey) match { case Some(rate) => Some(amount.multiply(rate)) case None if allowInverse => val invCurrencyKey = (to, from) rates.getSortedKeyFloorValue(invCurrencyKey, dateKey) match { case Some(rate) => Some(amount.divide(rate, java.math.RoundingMode.HALF_EVEN)) case _ => None } case _ => None } applyErrorHandling(converted, amount, from, to, date) } private[this] def applyErrorHandling(convertedAmount: Option[java.math.BigDecimal], origAmount: java.math.BigDecimal, from: String, to: String, date: String): Try[Option[java.math.BigDecimal]] = { convertedAmount match { case Some(_converted) => Success(Some(_converted)) case None if errorHandling.equalsIgnoreCase(ERROR_HANDLING_FAIL) => Failure(new ConversionRateNotFoundException( s"Rate for [$from] to [$to] conversion >= [$date] does not exist")) case None if errorHandling.equalsIgnoreCase(ERROR_HANDLING_NULL) => Success(None) case None if errorHandling.equalsIgnoreCase(ERROR_HANDLING_KEEP) => Success(Some(origAmount)) } } }
Example 6
Source File: CaseSensitivityUtils.scala From HANAVora-Extensions with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.catalyst import org.apache.spark.sql.SQLContext import org.apache.spark.sql.catalyst.analysis.{Analyzer, Catalog} import org.apache.spark.sql.types.{StructField, StructType} import org.apache.spark.sql.util.CollectionUtils._ import scala.util.{Failure, Success, Try} case class DuplicateFieldsException( originalSchema: StructType, schema: StructType, duplicateFields: Set[String]) extends RuntimeException( s"""Given schema contains duplicate fields after applying case sensitivity rules: |${duplicateFields.mkString(", ")} |Given schema: |$originalSchema |After applying case sensitivity rules: |$schema """.stripMargin) }
Example 7
Source File: TestUtils.scala From HANAVora-Extensions with Apache License 2.0 | 5 votes |
package com.sap.spark.util import java.util.Locale import scala.io.Source import org.apache.spark.SparkContext import org.apache.spark.rdd.RDD import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.{Row, SQLContext, SapSQLContext} import org.apache.spark.sql.hive.SapHiveContext import org.apache.spark.sql.sources.sql.SqlLikeRelation import org.apache.spark.sql.sources.{BaseRelation, CatalystSource, Table} import org.apache.spark.sql.types.StructType import org.mockito.Matchers._ import org.mockito.Mockito._ import scala.tools.nsc.io.Directory import scala.util.{Failure, Success} def parsePTestFile(fileName: String): List[(String, String, String)] = { val filePath = getFileFromClassPath(fileName) val fileContents = Source.fromFile(filePath).getLines .map(p => p.stripMargin.trim) .filter(p => !p.isEmpty && !p.startsWith("//")) // filter empty rows and comments .mkString("\n") val p = new PTestFileParser // strip semicolons from query and parsed p(fileContents) match { case Success(lines) => lines.map { case (query, parsed, expect) => (stripSemicolon(query).trim, stripSemicolon(parsed).trim, expect.trim) } case Failure(ex) => throw ex } } private def stripSemicolon(sql: String): String = if (sql.endsWith(";")) { sql.substring(0, sql.length-1) } else { sql } def withTempDirectory[A](f: Directory => A): A = { val dir = Directory.makeTemp() try { f(dir) } finally { dir.deleteIfExists() } } }
Example 8
Source File: AuthenticationFilter.scala From maha with Apache License 2.0 | 5 votes |
// Copyright 2018, Oath Inc. // Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms. package filter import akka.stream.Materializer import com.google.common.base.Charsets import com.google.common.hash.Hashing import com.yahoo.maha.core.auth.{AuthValidator, ValidationResult} import play.api.Logger import play.api.mvc._ import scala.concurrent.Future import scala.util.{Failure, Success, Try} class AuthenticationFilter(authValidator: AuthValidator)(implicit val mat: Materializer) extends Filter { private val routesWhichRequireAuth : Set[String] = Set("/segments", "/overlord/workers", "/lookups", "/kill/segments") def apply(nextFilter: RequestHeader => Future[Result]) (requestHeader: RequestHeader): Future[Result] = { if(routesWhichRequireAuth.contains(requestHeader.path)) { Try { val result: ValidationResult = authValidator.validate(requestHeader) result } match { case Success(result) => val requestHeaderWithId = requestHeader.copy(tags = requestHeader.tags + ("X-Request-Id" -> generateRequestId(requestHeader)) + ("userId" -> result.user.getOrElse("Authorized User"))) nextFilter(requestHeaderWithId) case Failure(e) => Logger.error(s"Exception while authenticating user", e) val result: Result = authValidator.handleAuthFailure(requestHeader) Future.successful(result) } } else { Logger.debug(s"no auth required for path : ${requestHeader.path}") nextFilter(requestHeader) } } private def generateRequestId(requestHeader: RequestHeader): String = { return s" ${Hashing.goodFastHash(128).newHasher.putString(requestHeader.path + requestHeader.queryString, Charsets.UTF_8).hash.asLong}-${System.nanoTime}" } }
Example 9
Source File: ThrottlingConfig.scala From maha with Apache License 2.0 | 5 votes |
package com.yahoo.maha.worker.throttling import java.util.concurrent.Executors import com.yahoo.maha.core.Engine import com.yahoo.maha.job.service.{JobMetadata, JobStatus, JobType} import com.yahoo.maha.worker.request.MahaWorkerRequest import grizzled.slf4j.Logging import org.joda.time.{DateTime, DateTimeZone} import scala.concurrent.{Await, ExecutionContext} import scala.concurrent.duration._ import scala.util.{Failure, Success} case class EngineBasedThrottler(throttlingConfig: EngineThrottlingConfig, jobMetadata : JobMetadata, jobMetaExecConfig: JobMetaExecConfig) extends Throttler with Logging { implicit val executor = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(jobMetaExecConfig.poolSize)) override def throttle(mahaWorkerRequest: MahaWorkerRequest): Boolean = { val engine: Engine = mahaWorkerRequest.engine val jobType:JobType = { val jobTypeOption = JobType.getJobType(engine) require(jobTypeOption.isDefined, s"Unable to get the job type for engine $engine") jobTypeOption.get } var timesChecked = 0 var countOfRunningJobs = getRunningJobs(engine, jobType) while (countOfRunningJobs > throttlingConfig.countThreshold && timesChecked < throttlingConfig.maxChecks) { warn(s"Throttling: Number of running jobs ($countOfRunningJobs) exceeds threshold (${throttlingConfig.countThreshold}). Checked $timesChecked times.") Thread.sleep(throttlingConfig.checkDelayMs) countOfRunningJobs = getRunningJobs(engine, jobType) timesChecked += 1 } if (timesChecked == throttlingConfig.maxChecks && countOfRunningJobs > throttlingConfig.countThreshold) { warn(s"Timeout: Count of running jobs exceeds threshold even after ${throttlingConfig.checkDelayMs * throttlingConfig.maxChecks} ms. Continuing to process to avoid increasing PULSAR/KAFKA backlog.") //monManager.incrementMetric(Metrics.ThrottleCheckTimeouts) } info(s"Number of running jobs ($countOfRunningJobs) below threshold (${throttlingConfig.countThreshold}), proceeding to process message.") if(timesChecked > 0) { true } else false } def getRunningJobs(engine: Engine, jobType:JobType): Int = { try { val jobCreatedTs = DateTime.now(DateTimeZone.UTC).minusMinutes(throttlingConfig.lookbackMins) val countOfRunningJobsFuture = jobMetadata.countJobsByTypeAndStatus(jobType, JobStatus.RUNNING, jobCreatedTs) Await.result(countOfRunningJobsFuture, jobMetaExecConfig.maxWaitMills millis) val runningJobCount: Int = if(countOfRunningJobsFuture.value.isEmpty) { warn(s"Failed to get the runningJobCount in ${jobMetaExecConfig.maxWaitMills}") 0 } else { countOfRunningJobsFuture.value.get match { case Success(count) => count case Failure(t) => { error(s"Failed to get the result from jobMeta ${t.getMessage}", t) 0 } } } runningJobCount } catch { case e:Exception => e.printStackTrace() 0 } } }
Example 10
Source File: package.scala From maha with Apache License 2.0 | 5 votes |
// Copyright 2017, Yahoo Holdings Inc. // Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms. package com.yahoo.maha import java.io.Closeable import org.slf4j.LoggerFactory import scala.util.{Failure, Success, Try} package object report { private lazy val logger = LoggerFactory.getLogger("safeOperation") def safeOperation[A, B](operation: A)(cleanup: A => Unit)(doWork: A => B): Try[B] = { try { Success(doWork(operation)) } catch { case e: Exception => logger.error("Failed on safeOperation doWork", e) try { if (operation != null) { cleanup(operation) } } catch { case e: Exception => logger.error("Failed on safeOperation cleanup", e) } Failure(e) } } def safeCloseable[A <: Closeable, B](closeable: A)(doWork: A => B): Try[B] = { safeOperation(closeable)(_.close())(doWork) } }
Example 11
Source File: Unmarshallers.scala From JustinDB with Apache License 2.0 | 5 votes |
package justin.httpapi import java.util.UUID import akka.http.scaladsl.unmarshalling._ import akka.stream.Materializer import spray.json.{JsString, JsValue, JsonFormat, _} import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} object Unmarshallers { implicit val UuidFormat = new JsonFormat[UUID] { override def read(json: JsValue): UUID = { json match { case JsString(uuid) => Try(UUID.fromString(uuid)) match { case Success(parsedUuid) => parsedUuid case Failure(_) => deserializationError("UUID could not be created from given string") } case _ => deserializationError("UUID could not be converted to UUID object.") } } override def write(obj: UUID): JsValue = JsString(obj.toString) } object UUIDUnmarshaller extends FromStringUnmarshaller[UUID] { override def apply(value: String)(implicit ec: ExecutionContext, materializer: Materializer): Future[UUID] = { Future.apply(UUID.fromString(value)) } } }
Example 12
Source File: HttpRouter.scala From JustinDB with Apache License 2.0 | 5 votes |
package justin.httpapi import java.util.UUID import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import justin.db.Data import justin.db.client.{ActorRefStorageNodeClient, GetValueResponse, WriteValueResponse} import justin.db.replica.{R, W} import justin.db.storage.Base64 import justin.db.versioning.NodeIdVectorClockBase64 import justin.httpapi.JustinDirectives._ import justin.httpapi.Unmarshallers.UUIDUnmarshaller import spray.json.DefaultJsonProtocol._ import spray.json.RootJsonFormat import scala.concurrent.ExecutionContext import scala.util.{Failure, Success} object HttpRouter { import Unmarshallers.UuidFormat case class Result(value: String) implicit val valueFormat: RootJsonFormat[Result] = jsonFormat1(Result) case class ConflictedData(id: String, value: String, vclock: Base64) implicit val conflictedDataFormat: RootJsonFormat[ConflictedData] = jsonFormat3(ConflictedData) case class PutValue(id: UUID, value: String, w: Int) implicit val putValueFormat: RootJsonFormat[PutValue] = jsonFormat3(PutValue) } class HttpRouter(client: ActorRefStorageNodeClient)(implicit ec: ExecutionContext) { import HttpRouter._ private[this] def transformConflictedData(data: Data) = { val vcBase64 = new NodeIdVectorClockBase64().encode(data.vclock).get ConflictedData(data.id.toString, data.value, vcBase64) } def routes: Route = withVectorClockHeader { vClockHeader => { (get & path("get") & pathEndOrSingleSlash & parameters(('id.as(UUIDUnmarshaller), 'r.as[Int]))) { (uuid, r) => onComplete(client.get(uuid, R(r))) { case Success(GetValueResponse.Found(data)) => respondWithHeader(VectorClockHeader(data.vclock)) { complete(OK -> Result(data.value)) } case Success(GetValueResponse.Conflicts(data)) => complete(MultipleChoices -> data.map(transformConflictedData)) case Success(GetValueResponse.NotFound(id)) => complete(NotFound -> Result(s"Couldn't found value with id ${id.toString}")) case Success(GetValueResponse.Failure(err)) => complete(BadRequest -> Result(err)) case Failure(ex) => complete(InternalServerError -> Result(ex.getMessage)) } } } ~ (post & path("put") & pathEndOrSingleSlash & entity(as[PutValue])) { putValue => complete { client.write(Data(putValue.id, putValue.value, vClockHeader.vectorClock), W(putValue.w)).map[ToResponseMarshallable] { case WriteValueResponse.Success(id) => NoContent case WriteValueResponse.Conflict => MultipleChoices -> Result("Multiple Choices") case WriteValueResponse.Failure(err) => BadRequest -> Result(err) } } } } }
Example 13
Source File: YamlProjectOperationInfoParser.scala From rug with GNU General Public License v3.0 | 5 votes |
package com.atomist.project.common.yaml import java.util.regex.{Pattern, PatternSyntaxException} import com.atomist.param._ import com.atomist.project.common.template.{InvalidTemplateException, TemplateBasedProjectOperationInfo} import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper import org.apache.commons.lang3.builder.ReflectionToStringBuilder import scala.util.{Failure, Success, Try} object YamlProjectOperationInfoParser { private val mapper = new ObjectMapper(new YAMLFactory()) with ScalaObjectMapper mapper.registerModule(DefaultScalaModule) @throws[InvalidYamlDescriptorException] def parse(yaml: String): TemplateBasedProjectOperationInfo = { if (yaml == null || "".equals(yaml)) throw new InvalidYamlDescriptorException("YAML content required in template metadata file") Try(mapper.readValue(yaml, classOf[BoundProjectOperationInfo])) match { case s: Success[BoundProjectOperationInfo] => val badPatterns = s.value.parameters.flatMap(p => patternError(p)) if (badPatterns.nonEmpty) throw new InvalidYamlDescriptorException(s"Bad regexp patterns: ${badPatterns.mkString(",")}") s.value case f: Failure[BoundProjectOperationInfo] => throw new InvalidYamlDescriptorException(s"Failed to parse YAML [$yaml]: ${f.exception.getMessage}", f.exception) } } private def patternError(p: Parameter): Option[String] = { try { Pattern.compile(p.getPattern) None } catch { case pse: PatternSyntaxException => Some(s"${p.getName}: Bad regular expression pattern: ${pse.getMessage}") } } } private class BoundProjectOperationInfo extends TemplateBasedProjectOperationInfo { @JsonProperty("name") var name: String = _ @JsonProperty("description") var description: String = _ @JsonProperty("template_name") var templateName: String = _ @JsonProperty("type") var _templateType: String = _ override def templateType: Option[String] = if (_templateType == null || "".equals(_templateType)) None else Some(_templateType) @JsonProperty("parameters") private var _params: Seq[Parameter] = Nil @JsonProperty("tags") private var _tags: Seq[TagHolder] = Nil override def parameters: Seq[Parameter] = _params override def tags: Seq[Tag] = _tags.map(tw => tw.toTag) override def toString = ReflectionToStringBuilder.toString(this) } private class TagHolder { @JsonProperty var name: String = _ @JsonProperty var description: String = _ def toTag = Tag(name, description) } class InvalidYamlDescriptorException(msg: String, ex: Throwable = null) extends InvalidTemplateException(msg, ex)
Example 14
Source File: PlanUtils.scala From rug with GNU General Public License v3.0 | 5 votes |
package com.atomist.rug.runtime.plans import com.atomist.rug.spi.Handlers.Instruction._ import com.atomist.tree.utils.TreeNodePrinter import com.atomist.tree.utils.TreeNodePrinter.BabyTree import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.{Failure, Success} object PlanUtils { import com.atomist.rug.spi.Handlers._ def drawPlan(plan: Plan): String = { val tree: BabyTree = planToTree(plan) TreeNodePrinter.draw[BabyTree](_.children, _.print)(tree) } def drawEventLogs(name: String, events: Seq[PlanLogEvent]) = TreeNodePrinter.drawTree(awaitAndTreeLogEvents(name, events)) private def instructionToString(i: Instruction) = { val op = i match { case Generate(_) => "Generate" case Edit(_) => "Edit" case Command(_) => "Command" case Execute(_) => "Execute" case Respond(_) => "Respond" } s"$op ${i.detail.name} ${i.detail.coordinates} ${i.detail.parameters}" } private def messageToTree(m: Message) = { val messageString = s"Message: ${m.toDisplay}" BabyTree(messageString) } private def callbackToTree(name: String, c: Callback): BabyTree = BabyTree(name, Seq(c match { case p: Plan => planToTree(p) case m: Message => messageToTree(m) case r: Respond => BabyTree(instructionToString(r)) })) private def planToTree(plan: Plan): BabyTree = { def respondableToTree(plannable: Plannable): BabyTree = { val i = instructionToString(plannable.instruction) plannable match { case r: Respondable => val onSuccessChild = r.onSuccess.map(callbackToTree("onSuccess", _)) val onFailureChild = r.onFailure.map(callbackToTree("onFailure", _)) BabyTree(i, onSuccessChild.toSeq ++ onFailureChild) case nr: Nonrespondable => BabyTree(i, Nil) } } val allMessages = plan.local ++ plan.lifecycle BabyTree("Plan", plan.instructions.sortBy(_.toString).map(respondableToTree) ++ allMessages.sortBy(_.toDisplay).map(messageToTree)) } private def awaitAndTreeLogEvents(name: String, events: Seq[PlanLogEvent]): BabyTree = { def logEventToTree(one: PlanLogEvent): BabyTree = { def nullSafeMessage(x: Throwable) = s"Error: ${Option(x).map(_.getMessage).getOrElse("null exception")}" one match { case InstructionError(i, x) => BabyTree(nullSafeMessage(x), Seq(BabyTree(instructionToString(i)))) case MessageDeliveryError(m, x) => BabyTree(nullSafeMessage(x), Seq(messageToTree(m))) case CallbackError(c, x) => BabyTree(nullSafeMessage(x), Seq(callbackToTree("failed callback", c))) case InstructionResult(instruction, response) => BabyTree(s"Received $response back from ${instructionToString(instruction)}") case NestedPlanRun(plan, planResult) => val result = awaitAndTreeLogEvents(s"Future completed", planResult.log) val planChild = planToTree(plan) BabyTree("Nested plan run", Seq(planChild, result)) } } val children = events.map(logEventToTree) BabyTree(name, children.sortBy(_.print)) } }
Example 15
Source File: ProjectScenarioWorld.scala From rug with GNU General Public License v3.0 | 5 votes |
package com.atomist.rug.test.gherkin.project import com.atomist.param.{SimpleParameterValue, SimpleParameterValues} import com.atomist.project.archive.Rugs import com.atomist.project.common.InvalidParametersException import com.atomist.project.edit.{FailedModificationAttempt, ModificationAttempt, ProjectEditor, SuccessfulModification} import com.atomist.project.generate.ProjectGenerator import com.atomist.rug.RugNotFoundException import com.atomist.rug.kind.core.{ProjectContext, ProjectMutableView, RepoResolver} import com.atomist.rug.runtime.js.interop.NashornUtils import com.atomist.rug.runtime.js.{BaseRugContext, JavaScriptProjectOperation} import com.atomist.rug.test.gherkin._ import com.atomist.source.file.NamedFileSystemArtifactSourceIdentifier import com.atomist.source.git.{FileSystemGitArtifactSource, GitRepositoryCloner} import com.atomist.source.{ArtifactSource, EmptyArtifactSource} import scala.util.{Failure, Success, Try} private object ProjectGenerationContext extends BaseRugContext { override def repoResolver: Option[RepoResolver] = Some(GitRepoResolver) } private object GitRepoResolver extends RepoResolver { private val Cloner = GitRepositoryCloner() override def resolveBranch(owner: String, repoName: String, branch: String): ArtifactSource = Try(Cloner.clone(repo = repoName, owner = owner, branch = Some(branch))) match { case Success(dir) => FileSystemGitArtifactSource(NamedFileSystemArtifactSourceIdentifier(repoName, dir)) case Failure(e) => throw new IllegalArgumentException("Failed to clone repo", e) } override def resolveSha(owner: String, repoName: String, sha: String): ArtifactSource = Try(Cloner.clone(repo = repoName, owner = owner, sha = Some(sha))) match { case Success(dir) => FileSystemGitArtifactSource(NamedFileSystemArtifactSourceIdentifier(repoName, dir)) case Failure(e) => throw new IllegalArgumentException("Failed to clone repo", e) } }
Example 16
Source File: ScenarioWorld.scala From rug with GNU General Public License v3.0 | 5 votes |
package com.atomist.rug.test.gherkin import com.atomist.param.{ParameterValues, SimpleParameterValues} import com.atomist.project.archive.Rugs import com.atomist.project.common.InvalidParametersException import com.atomist.rug.kind.DefaultTypeRegistry import com.atomist.rug.kind.core.ProjectMutableView import com.atomist.rug.runtime.js.interop.NashornUtils import com.atomist.rug.spi.{TypeRegistry, Typed, UsageSpecificTypeRegistry} import com.atomist.rug.ts.{CortexTypeGenerator, DefaultTypeGeneratorConfig} import com.atomist.source.file.NamedFileSystemArtifactSourceIdentifier import com.atomist.source.git.{FileSystemGitArtifactSource, GitRepositoryCloner} import jdk.nashorn.api.scripting.ScriptObjectMirror import scala.util.{Failure, Success, Try} object ScenarioWorld { lazy val ExtendedTypes: TypeRegistry = CortexTypeGenerator.extendedTypes(DefaultTypeGeneratorConfig.CortexJson) } def invalidParameters: InvalidParametersException = ipe def logInvalidParameters(ipe: InvalidParametersException): Unit = this.ipe = ipe protected def parameters(params: Any): ParameterValues = params match { case som: ScriptObjectMirror => // The user has created a new JavaScript object, as in { foo: "bar" }, // to pass up as an argument to the invoked editor. Extract its properties SimpleParameterValues(NashornUtils.extractProperties(som)) case _ => SimpleParameterValues.Empty } protected case class RepoIdentification(owner: String, name: String, branch: Option[String], sha: Option[String]) def cloneRepo(cloneInfo: AnyRef): ProjectMutableView = { val rid = extractRepoId(cloneInfo) val cloner = new GitRepositoryCloner(oAuthToken = config.oAuthToken.getOrElse("")) Try(cloner.clone(rid.name, rid.owner, rid.branch, rid.sha)) match { case Success(dir) => val as = FileSystemGitArtifactSource(NamedFileSystemArtifactSourceIdentifier(rid.name, dir)) new ProjectMutableView(as) case Failure(e) => throw new IllegalArgumentException("Failed to clone repo", e) } } import NashornUtils._ protected def extractRepoId(o: AnyRef): RepoIdentification = o match { case som: ScriptObjectMirror => val owner = stringProperty(som, "owner") val name = stringProperty(som, "name") val branch = stringProperty(som, "branch") val sha = stringProperty(som, "sha") RepoIdentification(owner, name, Option(branch), Option(sha)) case x => throw new IllegalArgumentException(s"Required JavaScript object repo ID, not $x") } }
Example 17
Source File: DurationFormat.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.libs.json._ import scala.concurrent.duration._ import scala.concurrent.duration.ops.v4.DurationOps import scala.util.control.NonFatal import scala.util.{Failure, Success} object DurationFormat { def asString(duration: Duration): String = duration match { case inf: Duration.Infinite => asString(inf) case finite => finite.toString } def asString(inf: Duration.Infinite): String = inf.toString.substring("Duration.".length) object string extends StringDurationFormat { implicit val durationFormat: Format[Duration] = Format(durationReads, durationWrites) implicit val finiteDurationFormat: Format[FiniteDuration] = Format(finiteDurationReads, durationWrites) } object array extends ArrayDurationFormat { implicit val durationFormat: Format[Duration] = Format(durationReads, durationWrites) implicit val finiteDurationFormat: Format[FiniteDuration] = Format(finiteDurationReads, durationWrites) } }
Example 18
Source File: DurationFormat.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.libs.json._ import play.api.libs.json.ops.v4.ImplicitTupleFormats._ import scala.concurrent.duration._ import scala.concurrent.duration.ops.v4.DurationOps import scala.util.control.NonFatal import scala.util.{Failure, Success} object DurationFormat { def asString(duration: Duration): String = duration match { case inf: Duration.Infinite => asString(inf) case finite => finite.toString } def asString(inf: Duration.Infinite): String = inf.toString.substring("Duration.".length) object string extends StringDurationFormat { implicit val durationFormat: Format[Duration] = Format(durationReads, durationWrites) implicit val finiteDurationFormat: Format[FiniteDuration] = Format(finiteDurationReads, durationWrites) } object array extends ArrayDurationFormat { implicit val durationFormat: Format[Duration] = Format(durationReads, durationWrites) implicit val finiteDurationFormat: Format[FiniteDuration] = Format(finiteDurationReads, durationWrites) } }
Example 19
Source File: Binders.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources import org.joda.time.LocalDate import org.joda.time.format.DateTimeFormat import play.api.mvc.{PathBindable, QueryStringBindable} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.vatapi.models.{FinancialDataQueryParams, ObligationsQueryParams, OptEither} import scala.util.{Failure, Success, Try} object Binders { implicit def vrnBinder(implicit stringBinder: PathBindable[String]) = new PathBindable[Vrn] { val vrnRegex = """^\d{9}$""" def unbind(key: String, vrn: Vrn): String = stringBinder.unbind(key, vrn.value) def bind(key: String, value: String): Either[String, Vrn] = { if (value.matches(vrnRegex)) { Right(Vrn(value)) } else { Left("ERROR_VRN_INVALID") } } } implicit def obligationsQueryParamsBinder(implicit stringBinder: QueryStringBindable[String]) = new QueryStringBindable[ObligationsQueryParams] { override def bind(key: String, params: Map[String, Seq[String]]): OptEither[ObligationsQueryParams] = { val from = stringBinder.bind("from", params) val to = stringBinder.bind("to", params) val status = stringBinder.bind("status", params) val query = ObligationsQueryParams.from(from, to, status) if (query.isRight) Some(Right(query.right.get)) else Some(Left(query.left.get)) } override def unbind(key: String, value: ObligationsQueryParams): String = stringBinder.unbind(key, value.map(key).toString) } implicit def financialDataQueryParamsBinder(implicit stringBinder: QueryStringBindable[String]) = new QueryStringBindable[FinancialDataQueryParams] { override def bind(key: String, params: Map[String, Seq[String]]): OptEither[FinancialDataQueryParams] = { val from = stringBinder.bind("from", params) val to = stringBinder.bind("to", params) val query = FinancialDataQueryParams.from(from, to) if (query.isRight) Some(Right(query.right.get)) else Some(Left(query.left.get)) } override def unbind(key: String, value: FinancialDataQueryParams): String = stringBinder.unbind(key, value.map(key).toString) } val format: String = "yyy-MM-dd" implicit val dateQueryParamsBinder = new QueryStringBindable[LocalDate] { override def unbind(key: String, date: LocalDate): String = date.toString override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, LocalDate]] = for { dates <- params.get(key) } yield Try { DateTimeFormat.forPattern(format).parseLocalDate(dates(0)) } match { case Success(v) => Right(v) case Failure(_) => Left("ERROR_INVALID_DATE") } } }
Example 20
Source File: Response.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.Logger import play.api.http.Status import play.api.libs.json.JsValue import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.models.Errors import uk.gov.hmrc.vatapi.models.des.DesError import uk.gov.hmrc.vatapi.models.des.DesErrorCode.{DesErrorCode, _} import uk.gov.hmrc.vatapi.resources.{AuthRequest, VatResult} import uk.gov.hmrc.vatapi.utils.pagerDutyLogging.{Endpoint, PagerDutyLogging} import scala.PartialFunction.{apply => _, _} import scala.util.{Failure, Success, Try} object Response { val defaultCorrelationId = "No Correlation ID" def getCorrelationId(httpResponse: HttpResponse): String = httpResponse.header("CorrelationId").getOrElse(defaultCorrelationId) } trait Response { val logger: Logger = Logger(this.getClass) val status: Int = underlying.status def underlying: HttpResponse def filter[A](pf: PartialFunction[Int, VatResult])(implicit endpoint: Endpoint, request: AuthRequest[A]): VatResult = { val statusPrefix: Int = status / 100 statusPrefix match { case 4 | 5 => val message = s"DES error occurred. User type: ${request.authContext.affinityGroup}\n" + s"Status code: ${underlying.status}\nBody: ${underlying.body}" PagerDutyLogging.logError(endpoint.toLoggerMessage, message, statusPrefix, logger.error(_)) (pf orElse errorMappings orElse standardErrorMapping) (status) case _ => (pf andThen addCorrelationHeader) (status) } } private def addCorrelationHeader(result: VatResult) = underlying .header("CorrelationId") .fold(result)(correlationId => result.withHeaders("X-CorrelationId" -> correlationId)) def errorMappings: PartialFunction[Int, VatResult] = empty private def standardErrorMapping: PartialFunction[Int, VatResult] = { case 404 => VatResult.FailureEmptyBody(Status.NOT_FOUND, Errors.NotFound) case 500 if errorCodeIsOneOf(SERVER_ERROR) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 503 if errorCodeIsOneOf(SERVICE_UNAVAILABLE) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case _ => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) } def errorCodeIsOneOf(errorCodes: DesErrorCode*): Boolean = jsonOrError match { case Right(json) => json.asOpt[DesError].exists(errorCode => errorCodes.contains(errorCode.code)) case Left(_) => false } def jsonOrError: Either[Throwable, JsValue] = { Try(underlying.json) match { case Success(null) => Left(new RuntimeException) case Success(json) => Right(json) case Failure(e) => Left(e) } } def getCorrelationId: String = Response.getCorrelationId(underlying) }
Example 21
Source File: Obligations.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.models import com.github.nscala_time.time.OrderingImplicits import org.joda.time.LocalDate import play.api.libs.json._ import scala.util.{Failure, Success, Try} case class Obligations(obligations: Seq[Obligation]) object Obligations { implicit val writes: Writes[Obligations] = Json.writes[Obligations] } case class Obligation(start: LocalDate, end: LocalDate, due: LocalDate, status: String, periodKey: String, received: Option[LocalDate] = None) object Obligation { implicit val jodaDateWrites: Writes[LocalDate] = new Writes[LocalDate] { def writes(d: LocalDate): JsValue = JsString(d.toString()) } implicit val from = new DesTransformValidator[des.ObligationDetail, Obligation] { def from(desObligation: des.ObligationDetail) = { Try(Obligation( start = LocalDate.parse(desObligation.inboundCorrespondenceFromDate), end = LocalDate.parse(desObligation.inboundCorrespondenceToDate), due = LocalDate.parse(desObligation.inboundCorrespondenceDueDate), status = desObligation.status, periodKey = desObligation.periodKey, received = desObligation.inboundCorrespondenceDateReceived.map(LocalDate.parse)) ) match { case Success(obj) => Right(obj) case Failure(ex) => Left(InvalidDateError(s"Unable to parse the date from des response $ex")) } } } implicit val localDateOrder: Ordering[LocalDate] = OrderingImplicits.LocalDateOrdering implicit val ordering: Ordering[Obligation] = Ordering.by(_.start) implicit val writes: Writes[Obligation] = Json.writes[Obligation] } case class InvalidDateError(msg: String) extends DesTransformError
Example 22
Source File: PingPongCallDemoComponent.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.web.guide.views.rpc.demos import io.udash._ import io.udash.bootstrap._ import io.udash.bootstrap.button.UdashButton import io.udash.web.commons.views.Component import io.udash.web.guide.Context import io.udash.web.guide.styles.partials.GuideStyles import scalatags.JsDom import scalatags.JsDom.all._ import scala.util.{Failure, Success} class PingPongCallDemoComponent extends Component { import Context._ override def getTemplate: Modifier = PingPongCallDemoViewFactory() object PingPongCallDemoViewFactory { def apply(): Modifier = { val clientId = Property[Int](0) val presenter = new PingPongCallDemoPresenter(clientId) new PingPongCallDemoView(clientId, presenter).render } } class PingPongCallDemoPresenter(model: Property[Int]) { def onButtonClick(disabled: Property[Boolean]) = { disabled.set(true) Context.serverRpc.demos.pingDemo.fPing(model.get) onComplete { case Success(response) => model.set(response + 1) disabled.set(false) case Failure(_) => model.set(-1) } } } class PingPongCallDemoView(model: Property[Int], presenter: PingPongCallDemoPresenter) { import JsDom.all._ val pingDisabled = Property(false) val pingButton = UdashButton( buttonStyle = BootstrapStyles.Color.Primary.toProperty, disabled = pingDisabled, componentId = ComponentId("ping-pong-call-demo") )(nested => Seq[Modifier]("Ping(", nested(bind(model)), ")")) pingButton.listen { case UdashButton.ButtonClickEvent(_, _) => presenter.onButtonClick(pingDisabled) } def render: Modifier = span(GuideStyles.frame, GuideStyles.useBootstrap)( pingButton.render ) } }
Example 23
Source File: ClientIdDemoComponent.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.web.guide.views.rpc.demos import io.udash._ import io.udash.bootstrap._ import io.udash.bootstrap.button.UdashButton import io.udash.bootstrap.form.UdashInputGroup import io.udash.web.commons.views.Component import io.udash.web.guide.Context import io.udash.web.guide.styles.partials.GuideStyles import scalatags.JsDom import scalatags.JsDom.all._ import scala.util.{Failure, Success} class ClientIdDemoComponent extends Component { import Context._ override def getTemplate: Modifier = ClientIdDemoViewFactory() object ClientIdDemoViewFactory { def apply(): Modifier = { val clientId = Property[String]("???") val presenter = new ClientIdDemoPresenter(clientId) new ClientIdDemoView(clientId, presenter).render } } class ClientIdDemoPresenter(model: Property[String]) { def onButtonClick() = { Context.serverRpc.demos.clientIdDemo.clientId() onComplete { case Success(cid) => println(cid); model.set(cid) case Failure(ex) => println(ex); model.set(ex.toString) } } } class ClientIdDemoView(model: Property[String], presenter: ClientIdDemoPresenter) { import JsDom.all._ val loadIdButtonDisabled = Property(false) val loadIdButton = UdashButton( buttonStyle = BootstrapStyles.Color.Primary.toProperty, disabled = loadIdButtonDisabled, componentId = ComponentId("client-id-demo") )(_ => "Load client id") loadIdButton.listen { case UdashButton.ButtonClickEvent(_, _) => loadIdButtonDisabled.set(true) presenter.onButtonClick() } def render: Modifier = span(GuideStyles.frame, GuideStyles.useBootstrap)( UdashInputGroup()( UdashInputGroup.prependText( "Your client id: ", produce(model)(cid => span(id := "client-id-demo-response", cid).render) ), loadIdButton.render ).render ) } }
Example 24
Source File: NotificationsDemoComponent.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.web.guide.views.rpc.demos import io.udash._ import io.udash.bootstrap._ import io.udash.bootstrap.button.UdashButton import io.udash.bootstrap.form.UdashInputGroup import io.udash.web.commons.views.Component import io.udash.web.guide.demos.rpc.NotificationsClient import io.udash.web.guide.styles.partials.GuideStyles import scalatags.JsDom import scalatags.JsDom.all._ import scala.util.{Failure, Success} trait NotificationsDemoModel { def registered: Boolean def lastMessage: String } object NotificationsDemoModel extends HasModelPropertyCreator[NotificationsDemoModel] { implicit val blank: Blank[NotificationsDemoModel] = Blank.Simple(new NotificationsDemoModel { override def registered: Boolean = false override def lastMessage: String = "-" }) } class NotificationsDemoComponent extends Component { import io.udash.web.guide.Context._ override def getTemplate: Modifier = NotificationsDemoViewFactory() object NotificationsDemoViewFactory { def apply(): Modifier = { val model = ModelProperty.blank[NotificationsDemoModel] val presenter = new NotificationsDemoPresenter(model) new NotificationsDemoView(model, presenter).render } } class NotificationsDemoPresenter(model: ModelProperty[NotificationsDemoModel]) { private val demoListener = (msg: String) => model.subProp(_.lastMessage).set(msg) def onButtonClick(disabled: Property[Boolean]): Unit = { disabled.set(true) if (model.subProp(_.registered).get) { NotificationsClient.unregisterListener(demoListener) onComplete { case Success(_) => model.subProp(_.registered).set(false) disabled.set(false) case Failure(_) => model.subProp(_.registered).set(true) disabled.set(false) } } else { NotificationsClient.registerListener(demoListener) onComplete { case Success(_) => model.subProp(_.registered).set(true) disabled.set(false) case Failure(_) => model.subProp(_.registered).set(false) disabled.set(false) } } } } class NotificationsDemoView(model: ModelProperty[NotificationsDemoModel], presenter: NotificationsDemoPresenter) { import JsDom.all._ val registerDisabled = Property(false) val registerButton = UdashButton( buttonStyle = BootstrapStyles.Color.Primary.toProperty, disabled = registerDisabled, componentId = ComponentId("notifications-demo") )(nested => nested(produce(model.subProp(_.registered))( p => span(if (!p) "Register for notifications" else "Unregister").render ))) registerButton.listen { case UdashButton.ButtonClickEvent(_, _) => presenter.onButtonClick(registerDisabled) } def render: Modifier = span(GuideStyles.frame, GuideStyles.useBootstrap)( UdashInputGroup()( UdashInputGroup.prependText( span(id := "notifications-demo-response")( "Last message: ", bind(model.subProp(_.lastMessage)) ) ), registerButton.render ).render ) } }
Example 25
Source File: MarkdownView.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.web.commons.views import com.avsystem.commons._ import com.avsystem.commons.misc.AbstractCase import io.udash._ import io.udash.bootstrap._ import io.udash.bootstrap.alert.UdashAlert import io.udash.web.guide.markdown.{MarkdownPage, MarkdownPageRPC} import io.udash.web.guide.styles.MarkdownStyles import scala.util.{Failure, Success} trait MarkdownPageState extends State { def page: MarkdownPage } final case class MarkdownModel( content: String = "", error: String = "" ) object MarkdownModel extends HasModelPropertyCreator[MarkdownModel] { implicit val blank: Blank[MarkdownModel] = Blank.Simple(apply()) } final case class MarkdownPageViewFactory[T <: MarkdownPageState]()( rpc: MarkdownPageRPC ) extends AbstractCase with ViewFactory[T] { override def create(): (MarkdownView, MarkdownPresenter[T]) = { val model: ModelProperty[MarkdownModel] = ModelProperty.blank (new MarkdownView(model), new MarkdownPresenter[T](model, rpc)) } } final class MarkdownPresenter[T <: MarkdownPageState]( model: ModelProperty[MarkdownModel], rpc: MarkdownPageRPC ) extends Presenter[T] { override def handleState(state: T): Unit = { model.set(MarkdownModel.blank.value) rpc.loadContent(state.page).onCompleteNow { case Success(rawHtml) => model.subProp(_.content).set(rawHtml) case Failure(exception) => model.subProp(_.error).set(exception.toString) } } } final class MarkdownView(model: ReadableModelProperty[MarkdownModel]) extends View { import io.udash.css.CssView._ import scalatags.JsDom.all._ override val getTemplate: Modifier = ISeq( produce(model.roSubProp(_.error)) { error => error.opt.filter(_.nonEmpty).map(e => div(cls := "bootstrap")( h1("Oops! Something went wrong :("), p("An error occurred during rendering your page:"), UdashAlert(alertStyle = BootstrapStyles.Color.Danger.toProperty)(e).render ).render ).toList }, produce(model.roSubProp(_.content)) { content => content.opt.filter(_.nonEmpty).map(c => div(MarkdownStyles.markdownPage)(raw(c)).render ).toList } ) }
Example 26
Source File: RestResponse.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash package rest.raw import com.avsystem.commons._ import com.avsystem.commons.misc.ImplicitNotFound import com.avsystem.commons.rpc.{AsRaw, AsReal} import scala.annotation.implicitNotFound import scala.util.Failure final case class RestResponse(code: Int, headers: IMapping[PlainValue], body: HttpBody) { def header(name: String, value: String): RestResponse = copy(headers = headers.append(name, PlainValue(value))) def isSuccess: Boolean = code >= 200 && code < 300 def toHttpError: HttpErrorException = HttpErrorException(code, body.textualContentOpt.toOptArg) def ensureNonError: RestResponse = if (isSuccess) this else throw toHttpError } object RestResponse extends RestResponseLowPrio { def plain(status: Int, message: OptArg[String] = OptArg.Empty): RestResponse = RestResponse(status, IMapping.empty, HttpBody.plain(message)) class LazyOps(private val resp: () => RestResponse) extends AnyVal { def recoverHttpError: RestResponse = try resp() catch { case e: HttpErrorException => e.toResponse } } implicit def lazyOps(resp: => RestResponse): LazyOps = new LazyOps(() => resp) implicit class AsyncOps(private val asyncResp: RawRest.Async[RestResponse]) extends AnyVal { def recoverHttpError: RawRest.Async[RestResponse] = callback => asyncResp { case Failure(e: HttpErrorException) => callback(Success(e.toResponse)) case tr => callback(tr) } } implicit def effectFromAsyncResp[F[_], T]( implicit asyncEff: RawRest.AsyncEffect[F], asResponse: AsReal[RestResponse, T] ): AsReal[RawRest.Async[RestResponse], Try[F[T]]] = async => Success(asyncEff.fromAsync(RawRest.mapAsync(async)(resp => asResponse.asReal(resp)))) implicit def effectToAsyncResp[F[_], T]( implicit asyncEff: RawRest.AsyncEffect[F], asResponse: AsRaw[RestResponse, T] ): AsRaw[RawRest.Async[RestResponse], Try[F[T]]] = _.fold(RawRest.failingAsync, ft => RawRest.mapAsync(asyncEff.toAsync(ft))(asResponse.asRaw)).recoverHttpError // following two implicits provide nice error messages when serialization is lacking for HTTP method result // while the async wrapper is fine (e.g. Future) @implicitNotFound("${F}[${T}] is not a valid result type because:\n#{forResponseType}") implicit def effAsyncAsRealNotFound[F[_], T](implicit fromAsync: RawRest.AsyncEffect[F], forResponseType: ImplicitNotFound[AsReal[RestResponse, T]] ): ImplicitNotFound[AsReal[RawRest.Async[RestResponse], Try[F[T]]]] = ImplicitNotFound() @implicitNotFound("${F}[${T}] is not a valid result type because:\n#{forResponseType}") implicit def effAsyncAsRawNotFound[F[_], T](implicit toAsync: RawRest.AsyncEffect[F], forResponseType: ImplicitNotFound[AsRaw[RestResponse, T]] ): ImplicitNotFound[AsRaw[RawRest.Async[RestResponse], Try[F[T]]]] = ImplicitNotFound() // following two implicits provide nice error messages when result type of HTTP method is totally wrong @implicitNotFound("#{forResponseType}") implicit def asyncAsRealNotFound[T]( implicit forResponseType: ImplicitNotFound[HttpResponseType[T]] ): ImplicitNotFound[AsReal[RawRest.Async[RestResponse], Try[T]]] = ImplicitNotFound() @implicitNotFound("#{forResponseType}") implicit def asyncAsRawNotFound[T]( implicit forResponseType: ImplicitNotFound[HttpResponseType[T]] ): ImplicitNotFound[AsRaw[RawRest.Async[RestResponse], Try[T]]] = ImplicitNotFound() } trait RestResponseLowPrio { this: RestResponse.type => implicit def bodyBasedFromResponse[T](implicit bodyAsReal: AsReal[HttpBody, T]): AsReal[RestResponse, T] = resp => bodyAsReal.asReal(resp.ensureNonError.body) implicit def bodyBasedToResponse[T](implicit bodyAsRaw: AsRaw[HttpBody, T]): AsRaw[RestResponse, T] = value => bodyAsRaw.asRaw(value).defaultResponse.recoverHttpError // following two implicits forward implicit-not-found error messages for HttpBody as error messages for RestResponse @implicitNotFound("Cannot deserialize ${T} from RestResponse, because:\n#{forBody}") implicit def asRealNotFound[T]( implicit forBody: ImplicitNotFound[AsReal[HttpBody, T]] ): ImplicitNotFound[AsReal[RestResponse, T]] = ImplicitNotFound() @implicitNotFound("Cannot serialize ${T} into RestResponse, because:\n#{forBody}") implicit def asRawNotFound[T]( implicit forBody: ImplicitNotFound[AsRaw[HttpBody, T]] ): ImplicitNotFound[AsRaw[RestResponse, T]] = ImplicitNotFound() }
Example 27
Source File: JettyRestClient.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash package rest.jetty import java.net.HttpCookie import java.nio.charset.Charset import com.avsystem.commons._ import com.avsystem.commons.annotation.explicitGenerics import io.udash.rest.raw._ import io.udash.utils.URLEncoder import org.eclipse.jetty.client.HttpClient import org.eclipse.jetty.client.api.Result import org.eclipse.jetty.client.util.{BufferingResponseListener, BytesContentProvider, StringContentProvider} import org.eclipse.jetty.http.{HttpHeader, MimeTypes} import scala.util.{Failure, Success} import scala.concurrent.duration._ object JettyRestClient { final val DefaultMaxResponseLength = 2 * 1024 * 1024 final val DefaultTimeout = 10.seconds @explicitGenerics def apply[RestApi: RawRest.AsRealRpc : RestMetadata]( client: HttpClient, baseUri: String, maxResponseLength: Int = DefaultMaxResponseLength, timeout: Duration = DefaultTimeout ): RestApi = RawRest.fromHandleRequest[RestApi](asHandleRequest(client, baseUri, maxResponseLength, timeout)) def asHandleRequest( client: HttpClient, baseUrl: String, maxResponseLength: Int = DefaultMaxResponseLength, timeout: Duration = DefaultTimeout ): RawRest.HandleRequest = RawRest.safeHandle { request => callback => val path = baseUrl + PlainValue.encodePath(request.parameters.path) val httpReq = client.newRequest(baseUrl).method(request.method.name) httpReq.path(path) request.parameters.query.entries.foreach { case (name, PlainValue(value)) => httpReq.param(name, value) } request.parameters.headers.entries.foreach { case (name, PlainValue(value)) => httpReq.header(name, value) } request.parameters.cookies.entries.foreach { case (name, PlainValue(value)) => httpReq.cookie(new HttpCookie( URLEncoder.encode(name, spaceAsPlus = true), URLEncoder.encode(value, spaceAsPlus = true))) } request.body match { case HttpBody.Empty => case tb: HttpBody.Textual => httpReq.content(new StringContentProvider(tb.contentType, tb.content, Charset.forName(tb.charset))) case bb: HttpBody.Binary => httpReq.content(new BytesContentProvider(bb.contentType, bb.bytes)) } timeout match { case fd: FiniteDuration => httpReq.timeout(fd.length, fd.unit) case _ => } httpReq.send(new BufferingResponseListener(maxResponseLength) { override def onComplete(result: Result): Unit = if (result.isSucceeded) { val httpResp = result.getResponse val contentTypeOpt = httpResp.getHeaders.get(HttpHeader.CONTENT_TYPE).opt val charsetOpt = contentTypeOpt.map(MimeTypes.getCharsetFromContentType) val body = (contentTypeOpt, charsetOpt) match { case (Opt(contentType), Opt(charset)) => HttpBody.textual(getContentAsString, MimeTypes.getContentTypeWithoutCharset(contentType), charset) case (Opt(contentType), Opt.Empty) => HttpBody.binary(getContent, contentType) case _ => HttpBody.Empty } val headers = httpResp.getHeaders.iterator.asScala.map(h => (h.getName, PlainValue(h.getValue))).toList val response = RestResponse(httpResp.getStatus, IMapping(headers), body) callback(Success(response)) } else { callback(Failure(result.getFailure)) } }) } }
Example 28
Source File: ClientMain.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash package rest.examples import io.udash.rest.SttpRestClient import sttp.client.SttpBackend import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.util.{Failure, Success} object ClientMain { def main(args: Array[String]): Unit = { implicit val sttpBackend: SttpBackend[Future, Nothing, Nothing] = SttpRestClient.defaultBackend() val proxy: UserApi = SttpRestClient[UserApi]("http://localhost:9090") // make a remote REST call val result: Future[User] = proxy.createUser("Fred") // use whatever execution context is appropriate import scala.concurrent.ExecutionContext.Implicits.global result.onComplete { case Success(user) => println(s"User $user created") case Failure(cause) => cause.printStackTrace() } // just wait until future is complete so that main thread doesn't finish prematurely Await.ready(result, 10.seconds) } }
Example 29
Source File: AttrTranslationModifier.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.i18n.bindings import com.avsystem.commons._ import io.udash.i18n.Translated import io.udash.logging.CrossLogging import org.scalajs.dom.Element import scalatags.JsDom.Modifier import scala.concurrent.Future import scala.util.{Failure, Success} private[i18n] class AttrTranslationModifier(translation: => Future[Translated], attr: String) extends Modifier with CrossLogging { override def applyTo(t: Element): Unit = translation.onCompleteNow { case Success(text) => t.setAttribute(attr, text.string) case Failure(ex) => logger.error(ex.getMessage) } }
Example 30
Source File: TranslationModifier.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.i18n.bindings import com.avsystem.commons._ import io.udash.bindings.Bindings import io.udash.bindings.modifiers._ import io.udash.i18n._ import io.udash.logging.CrossLogging import org.scalajs.dom._ import scalatags.JsDom.Modifier import scala.concurrent.Future import scala.util.{Failure, Success} private[i18n] class TranslationModifier( translation: => Future[Translated], placeholder: Option[Element], rawHtml: Boolean ) extends Modifier with CrossLogging { protected final def update(t: Element, holder: Seq[Node]): Future[Seq[Node]] = { translation.transformNow { case Success(Translated(text)) => val newHolder: Seq[Node] = parseTranslation(rawHtml, text) t.replaceChildren(holder, newHolder) Success(newHolder) case Failure(ex) => logger.error(ex.getMessage) Success(holder) } } override def applyTo(t: Element): Unit = { val holder: Seq[Node] = Seq(t.appendChild(placeholder.getOrElse(Bindings.emptyStringNode()))) update(t, holder).discard } }
Example 31
Source File: package.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.i18n import org.scalajs.dom._ import scala.scalajs.js.{JavaScriptException, SyntaxError} import scala.util.{Failure, Success, Try} package object bindings { def parseTranslation(rawHtml: Boolean, text: String): Seq[Node] = if (rawHtml) Try { val wrapper = document.createElement("div") wrapper.innerHTML = text wrapper.childNodes } match { case Success(children) if children.length > 0 => (0 until children.length).map(children.item) case Success(_) | Failure(JavaScriptException(_: SyntaxError)) => Seq(document.createTextNode(text)) } else Seq(document.createTextNode(text)) }
Example 32
Source File: OAuthToken.scala From spark-power-bi with Apache License 2.0 | 5 votes |
package com.granturing.spark.powerbi import java.util.concurrent.{ExecutionException, TimeUnit, Executors} import com.microsoft.aad.adal4j.{AuthenticationResult, AuthenticationCallback, AuthenticationContext} import dispatch._ import org.apache.spark.Logging import scala.concurrent.{Await, promise} import scala.util.{Try, Failure, Success} private class OAuthReq(token: OAuthTokenHandler) extends (Req => Req) { override def apply(req: Req): Req = { req <:< Map("Authorization" -> s"Bearer ${token()}") } } private class OAuthTokenHandler(authConf: ClientConf, initialToken: Option[String] = None) extends Logging { private var _token: Option[String] = initialToken def apply(refresh: Boolean = false): String = { _token match { case Some(s) if !refresh => s case _ => { refreshToken match { case Success(s) => { _token = Some(s) s } case Failure(e) => throw e } } } } private def refreshToken: Try[String] = { log.info("refreshing OAuth token") val service = Executors.newFixedThreadPool(1); val context = new AuthenticationContext(authConf.token_uri, true, service) val p = promise[AuthenticationResult] val future = p.future context.acquireToken(authConf.resource, authConf.clientid, authConf.username, authConf.password, new AuthenticationCallback { def onSuccess(result: AuthenticationResult): Unit = { p.success(result) } def onFailure(ex: Throwable): Unit = { p.failure(ex) } }) try { val result = Await.result(future, authConf.timeout) log.info("OAuth token refresh successful") Success(result.getAccessToken) } catch { case e: ExecutionException => Failure(e.getCause) case t: Throwable => Failure(t) } finally { service.shutdown() } } }
Example 33
Source File: UpdateChecker.scala From kotlin-plugin with MIT License | 5 votes |
package kotlin import java.io.{InputStreamReader, BufferedReader, StringWriter} import argonaut._, Argonaut._ import scala.concurrent.Future import scala.util.{Failure, Success} object UpdateChecker { import scala.concurrent.ExecutionContext.Implicits.global type Result = (Set[String],String) type Callback[A] = Either[Throwable,Result] => A def apply[A](user: String, repo: String, name: String)(result: Callback[A]): Unit = { val bintray = new java.net.URL( s"https://api.bintray.com/packages/$user/$repo/$name") Future { val uc = bintray.openConnection() val in = new BufferedReader(new InputStreamReader(uc.getInputStream, "utf-8")) try { val sw = new StringWriter val buf = Array.ofDim[Char](8192) Stream.continually(in.read(buf, 0, 8192)) takeWhile ( _ != -1) foreach (sw.write(buf, 0, _)) sw.toString } finally { in.close() } } onComplete { case Success(json) => val decoded = json.decode[PackageInfo] val res: Either[Throwable, Result] = decoded match { case Left(Left(str)) => Left(new IllegalArgumentException(str)) case Left(Right(cursorHistory)) => Left(new IllegalArgumentException(cursorHistory._1)) case Right(packageInfo) => Right(packageInfo.versions.toSet -> packageInfo.version) } result(res) case Failure(t) => result(Left(t)) } } implicit def PackageInfoCodecJson: CodecJson[PackageInfo] = casecodec3( PackageInfo.apply, PackageInfo.unapply)("name", "latest_version", "versions") case class PackageInfo(name: String, version: String, versions: List[String]) }
Example 34
Source File: ApiDependantController.scala From ledger-manager-chrome with MIT License | 5 votes |
package co.ledger.manager.web.controllers.manager import java.util.Date import biz.enef.angulate.Scope import co.ledger.manager.web.services.ApiService import scala.concurrent.Future import scala.scalajs.js import scala.scalajs.js.timers import scala.scalajs.js.timers._ import scala.util.{Failure, Success} import scala.concurrent.ExecutionContext.Implicits.global trait ApiDependantController { val apiService: ApiService val $scope: Scope private var _loading = false def isLoading() = _loading def onBeforeRefresh(): Unit = {} def onAfterRefresh(): Unit = {} def refresh(): Unit = { onBeforeRefresh() _loading = !apiService.applications.isCompleted val startDate = new Date().getTime val applyUi = {() => if (_loading) { import timers._ val wait = Math.max(1500, new Date().getTime - startDate) setTimeout(wait) { _loading = false $scope.$apply() } } else { _loading = false $scope.$apply() } } apiService.firmwares flatMap {(_) => apiService.applications } onComplete { case Success(apps) => onAfterRefresh() applyUi() case Failure(ex) => ex.printStackTrace() applyUi() } } def fullRefresh(): Unit = { if (!_loading) { apiService.refresh() refresh() } } }
Example 35
Source File: BatchAppListController.scala From ledger-manager-chrome with MIT License | 5 votes |
package co.ledger.manager.web.controllers.manager import biz.enef.angulate.Module.RichModule import biz.enef.angulate.{Controller, Scope} import biz.enef.angulate.core.Location import co.ledger.manager.web.Application import co.ledger.manager.web.services.{DeviceService, WindowService} import scala.concurrent.Future import scala.scalajs.js import scala.scalajs.js.JSON import scala.util.{Failure, Success} import scala.concurrent.ExecutionContext.Implicits.global class BatchAppListController(val windowService: WindowService, deviceService: DeviceService, override val $scope: Scope, $route: js.Dynamic, $location: Location, $routeParams: js.Dictionary[String]) extends Controller with ManagerController { var applications = js.Array[js.Dictionary[js.Any]]() def fetchApplications(): Future[Unit] = { val provider = if (!js.isUndefined(js.Dynamic.global.LEDGER) && js.Dynamic.global.LEDGER.asInstanceOf[Boolean] == true) "?provider=ledger" else "" Application.httpClient.get("/applications" + provider).json map { case (json, _) => if (json.has("nanos")) { val apps = json.getJSONArray("nanos") applications = JSON.parse(apps.toString).asInstanceOf[js.Array[js.Dictionary[js.Any]]] } } } def isChecked(application: js.Dynamic): Boolean = { BatchAppListController.SELECTED_APPS.contains(application.identifier.asInstanceOf[String]) } def toggle(application: js.Dynamic): Unit = { if (isChecked(application)) { BatchAppListController.SELECTED_APPS = BatchAppListController.SELECTED_APPS.filter(_ != application.identifier.asInstanceOf[String]) } else { BatchAppListController.SELECTED_APPS = BatchAppListController.SELECTED_APPS :+ application.identifier.asInstanceOf[String] } } def back(): Unit = { $location.path("/applist/") $route.reload() } def installBatch(): Unit = { val apps = applications.filter({(item) => isChecked(item.asInstanceOf[js.Dynamic])}).map(_.asInstanceOf[js.Dynamic]) ApplyUpdateController.APP_BATCH = apps.toArray $location.path(s"/apply/batch/application/${js.Dynamic.global.encodeURIComponent(apps(0).name)}/${JSON.stringify(apps(0).app)}/") } def refresh(): Unit = { applications = js.Array[js.Dictionary[js.Any]]() fetchApplications() onComplete { case Success(_) => $scope.$apply() case Failure(ex) => ex.printStackTrace() } } refresh() } object BatchAppListController { // Don't do that var SELECTED_APPS = Array[String]() def init(module: RichModule) = { module.controllerOf[BatchAppListController]("BatchAppListController") } }
Example 36
Source File: UsbHidExchangePerformer.scala From ledger-manager-chrome with MIT License | 5 votes |
package co.ledger.manager.web.core.device.usb import co.ledger.wallet.core.device.Device.CommunicationException import co.ledger.wallet.core.utils.HexUtils import co.ledger.wallet.core.utils.logs.{Loggable, Logger} import co.ledger.manager.web.core.device.LedgerTransportHelper import co.ledger.manager.web.core.device.usb.UsbDeviceImpl.UsbExchangePerformer import scala.collection.mutable.ArrayBuffer import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{Future, Promise} import scala.scalajs.js import scala.scalajs.js.UndefOr import scala.util.{Failure, Success} class UsbHidExchangePerformer(connection: UsbDeviceImpl.Connection, var debug: Boolean, var useLedgerTransport: Boolean ) extends UsbExchangePerformer with Loggable { override implicit val LogTag: String = "APDU" val HidBufferSize = 64 val LedgerDefaultChannel = 0x1000 val Sw1DataAvailable = 0x61 private val chrome = js.Dynamic.global.chrome override def close(): Unit = { chrome.hid.disconnect(connection.connectionId) } override def performExchange(cmd: Array[Byte]): Future[Array[Byte]] = { var command = cmd if (useLedgerTransport) { command = LedgerTransportHelper.wrapCommandAPDU(LedgerDefaultChannel, cmd, HidBufferSize) } def sendBlocks(offset: Int = 0): Future[Unit] = { val blockSize = if (command.length - offset > HidBufferSize) HidBufferSize else command.length - offset System.arraycopy(command, offset, _transferBuffer, 0, blockSize) send(_transferBuffer) flatMap {(_) => if (offset + blockSize < command.length) sendBlocks(offset + blockSize) else Future.successful() } } def receiveLegacyBlock(buffer: ArrayBuffer[Byte]): Future[Array[Byte]] = { null } def receiveLedgerBlock(buffer: ArrayBuffer[Byte]): Future[Array[Byte]] = { receive().flatMap {(response) => buffer ++= response val responseData = LedgerTransportHelper.unwrapResponseAPDU(LedgerDefaultChannel, buffer.toArray, HidBufferSize) if (responseData == null) { receiveLedgerBlock(buffer) } else { Future.successful(responseData) } } } def receiveBlocks(buffer: ArrayBuffer[Byte] = ArrayBuffer.empty[Byte]): Future[Array[Byte]] = { if (useLedgerTransport) receiveLedgerBlock(buffer) else receiveLegacyBlock(buffer) } sendBlocks().flatMap((_) => receiveBlocks()) andThen { case Success(result) => case Failure(ex) => ex.printStackTrace() } } private def send(bytes: Array[Byte]): Future[Unit] = { import scala.scalajs.js.typedarray._ val promise = Promise[Unit]() chrome.hid.send(connection.connectionId, 0, byteArray2Int8Array(bytes).buffer, { () => if (js.isUndefined(chrome.runtime.lastError)) promise.success() else promise.failure(CommunicationException(chrome.runtime.lastError.message.toString)) }) promise.future } private def receive(): Future[Array[Byte]] = { import scala.scalajs.js.typedarray._ val promise = Promise[Array[Byte]]() chrome.hid.receive(connection.connectionId, {(reportId: UndefOr[Int], data: TypedArray[_, _]) => if (js.isUndefined(chrome.runtime.lastError)) promise.success(int8Array2ByteArray(new Int8Array(data))) else promise.failure(CommunicationException(chrome.runtime.lastError.message.toString)) }) promise.future } private val _transferBuffer = new Array[Byte](HidBufferSize) }
Example 37
Source File: DatabaseDeclaration.scala From ledger-manager-chrome with MIT License | 5 votes |
package co.ledger.manager.web.core.database import co.ledger.manager.web.core.idb.IndexedDb import org.scalajs.dom.idb import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} trait DatabaseDeclaration { def name: String def version: Int def models: Seq[QueryHelper[_]] def open(): Future[idb.Database] = { IndexedDb.open(name, Some(version)) {(connection, transaction) => // Create all store for (model <- models) { model.creator.create(connection, transaction) } } andThen { case Success(connection) => _connection = Option(connection) case Failure(ex) => ex.printStackTrace() } } def obtainConnection(): Future[idb.Database] = { connection match { case Some(c) => Future.successful(c) case None => open() } } def close(): Unit = _connection.foreach(_.close()) def connection: Option[idb.Database] = _connection def delete() = IndexedDb.delete(name) private var _connection: Option[idb.Database] = None }
Example 38
Source File: ResponseHelper.scala From ledger-manager-chrome with MIT License | 5 votes |
package co.ledger.wallet.core.net import java.io.{ByteArrayOutputStream, StringWriter} import java.nio.charset.Charset import org.json.{JSONArray, JSONObject} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.scalajs.js import scala.util.{Failure, Success} object ResponseHelper { implicit class ResponseFuture(f: Future[HttpClient#Response]) { def json: Future[(JSONObject, HttpClient#Response)] = { f.string.map { case (body, response) => (new JSONObject(body), response) } } def jsonArray: Future[(JSONArray, HttpClient#Response)] = { f.string.map { case (body, response) => (new JSONArray(body), response) } } def string: Future[(String, HttpClient#Response)] = { f.bytes.map { case (body, response) => val writer = new StringWriter(body.length) body foreach {(char) => writer.append(char.toChar) } (writer.toString, response) } } def bytes: Future[(Array[Byte], HttpClient#Response)] = { f.map { response => val input = response.body val output = new ByteArrayOutputStream() val buffer = new Array[Byte](4096) var read = 0 while ({read = input.read(buffer); read} > 0) { output.write(buffer, 0, read) } val result = output.toByteArray input.close() output.close() (result, response) } } def noResponseBody: Future[HttpClient#Response] = { f.andThen { case Success(response) => response.body.close() response case Failure(cause) => throw cause } } } }
Example 39
Source File: Parser.scala From goggles with MIT License | 5 votes |
package goggles.macros.parse import goggles.macros.At import goggles.macros.lex.Token import goggles.macros.errors.{ErrorAt, SyntaxError} import scala.util.{Try, Success, Failure} private[goggles] object Parser { def parseAppliedLens(tokens: List[At[Token]]): Either[ErrorAt[Nothing], AST] = { tokens match { case Nil => Left(SyntaxError.EmptyError.at(0)) case At(Token.Hole, _) :: rest => parseAST(rest) case At(Token.Unrecognised(c), offset) :: _ => Left(SyntaxError.UnrecognisedChar(c).at(offset)) case At(token, offset) :: _ => Left(SyntaxError.NonInterpolatedStart(token).at(offset)) } } def parseUnappliedLens(tokens: List[At[Token]]): Either[ErrorAt[Nothing], AST] = { tokens match { case Nil => Left(SyntaxError.EmptyError.at(0)) case At(Token.Hole, offset) :: rest => parseAST(Token.Dot.at(offset-1) :: Token.Hole.at(offset) :: rest) case At(Token.Unrecognised(c), offset) :: _ => Left(SyntaxError.UnrecognisedChar(c).at(offset)) case At(token, offset) :: _ => Left(SyntaxError.NonInterpolatedStart(token).at(offset)) } } private def parseAST(tokens: List[At[Token]]): Either[ErrorAt[Nothing], AST] = { def loop(remaining: List[At[Token]], exprs: List[At[LensExpr]]): Either[ErrorAt[Nothing], AST] = { parseLensExpr(remaining) match { case (Nil, Right(lensExpr)) => val list = (lensExpr :: exprs).reverse Right(AST(list.head, list.tail)) case (rest, Right(lensExpr)) => loop(rest, lensExpr :: exprs) case (_, Left(err)) => Left(err) } } loop(tokens, Nil) } def parseLensExpr(tokens: List[At[Token]]): (List[At[Token]], Either[ErrorAt[Nothing], At[LensExpr]]) = { tokens match { case At(Token.Dot, _) :: tokenAt :: rest => (rest, parseLensRef(tokenAt).map(ref => LensExpr.Ref(ref).at(tokenAt.offset))) case At(Token.Dot, offset) :: Nil => (Nil, Left(SyntaxError.EndingDot.at(offset))) case At(Token.Star, offset) :: rest => (rest, Right(LensExpr.Each.at(offset))) case At(Token.Question, offset) :: rest => (rest, Right(LensExpr.Opt.at(offset))) case At(Token.OpenBracket,_) :: At(Token.CloseBracket, offset) :: rest => (rest, Left(SyntaxError.NoIndexSupplied.at(offset))) case At(Token.OpenBracket,_) :: tokenAt :: At(Token.CloseBracket,_) :: rest => (rest, parseIndex(tokenAt).map(ix => LensExpr.Indexed(ix).at(tokenAt.offset))) case Nil => (Nil, Left(SyntaxError.EmptyError.at(0))) case At(Token.OpenBracket, offset) :: rest if !rest.exists { case At(Token.CloseBracket,_) => true; case _ => false } => (rest, Left(SyntaxError.UnclosedOpenBracket.at(offset))) case At(Token.OpenBracket,_) :: At(token, offset) :: rest => (rest, Left(SyntaxError.InvalidIndexSupplied(token).at(offset))) case At(Token.CloseBracket, offset) :: rest => (rest, Left(SyntaxError.UnexpectedCloseBracket.at(offset))) case At(Token.Name(n), offset) :: rest => (rest, Left(SyntaxError.NameWithNoDot(n).at(offset))) case At(Token.Hole, offset) :: rest => (rest, Left(SyntaxError.InterpOpticWithNoDot.at(offset))) case At(Token.Unrecognised(c), offset) :: rest => (rest, Left(SyntaxError.UnrecognisedChar(c).at(offset))) } } def parseLensRef(tokenAt: At[Token]): Either[ErrorAt[Nothing], LensRef] = { tokenAt match { case At(Token.Name(name), _) => Right(LensRef.Named(name)) case At(Token.Hole, _) => Right(LensRef.Interpolated) case At(Token.CloseBracket, offset) => Left(SyntaxError.UnexpectedCloseBracket.at(offset)) case At(token, offset) => Left(SyntaxError.InvalidAfterDot(token).at(offset)) } } def parseIndex(tokenAt: At[Token]): Either[ErrorAt[Nothing], Index] = { tokenAt match { case At(Token.Name(intStr), offset) => Try(intStr.toInt) match { case Success(i) => Right(Index.Literal(i)) case Failure(_) => Left(SyntaxError.VerbatimIndexNotInt(intStr).at(offset)) } case At(Token.Hole, _) => Right(Index.Interpolated) case At(Token.CloseBracket, offset) => Left(SyntaxError.NoIndexSupplied.at(offset)) case At(x, offset) => Left(SyntaxError.InvalidIndexSupplied(x).at(offset)) } } }
Example 40
Source File: AwsIAMTests.scala From sbt-aws-lambda with Apache License 2.0 | 5 votes |
package com.gilt.aws.lambda import com.amazonaws.services.identitymanagement.model._ import scala.util.{Failure, Success, Try} import utest._ trait NotImplementedAmazonIdentityManagementWrapper extends wrapper.AmazonIdentityManagement { def listRoles(): Try[ListRolesResult] = ??? def createRole(req: CreateRoleRequest): Try[CreateRoleResult] = ??? } object AwsIAMTests extends TestSuite { val tests = Tests { "Get basic lambda role" - { "gets role if name match" - getSome "gets none if no name match" - getNoneNoMatch "gets none if failure" - getNoneFailure } "Create basic lambda role" - { "creates with name" - createWithName "creates return role arn" - createReturnsArn } } def getSome = { val client = new NotImplementedAmazonIdentityManagementWrapper { override def listRoles() = { val result = (new ListRolesResult).withRoles( new Role().withRoleName("a"), new Role().withRoleName("b"), new Role().withRoleName("c"), new Role().withRoleName(AwsIAM.BasicLambdaRoleName) ) Success(result) } } val result = new AwsIAM(client).basicLambdaRole() assert(result.nonEmpty) } def getNoneNoMatch = { val client = new NotImplementedAmazonIdentityManagementWrapper { override def listRoles() = { val result = (new ListRolesResult).withRoles( new Role().withRoleName("a"), new Role().withRoleName("b"), new Role().withRoleName("c") ) Success(result) } } val result = new AwsIAM(client).basicLambdaRole() assert(result.isEmpty) } def getNoneFailure = { val client = new NotImplementedAmazonIdentityManagementWrapper { override def listRoles() = { Failure(new Throwable) } } val result = new AwsIAM(client).basicLambdaRole() assert(result.isEmpty) } def createWithName = { val client = new NotImplementedAmazonIdentityManagementWrapper { override def createRole(req: CreateRoleRequest) = { assert(req.getRoleName() == AwsIAM.BasicLambdaRoleName) Failure(new Throwable) } } new AwsIAM(client).createBasicLambdaRole() } def createReturnsArn = { val arn = "my-role-arn" val client = new NotImplementedAmazonIdentityManagementWrapper { override def createRole(req: CreateRoleRequest) = { val role = new Role().withArn(arn) val result = new CreateRoleResult().withRole(role) Success(result) } } val result = new AwsIAM(client).createBasicLambdaRole() assert(result.isSuccess) assert(result.get == RoleARN(arn)) } }
Example 41
Source File: CodebaseAnalyzeAggregatorActor.scala From CodeAnalyzerTutorial with Apache License 2.0 | 5 votes |
package tutor import java.util.Date import akka.actor.{Actor, ActorLogging, ActorRef, Cancellable, Props, Terminated} import akka.routing.{ActorRefRoutee, RoundRobinRoutingLogic, Router} import tutor.CodebaseAnalyzeAggregatorActor.{AnalyzeDirectory, Complete, Report, Timeout} import tutor.SourceCodeAnalyzerActor.NewFile import tutor.utils.BenchmarkUtil import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} object CodebaseAnalyzeAggregatorActor { def props(): Props = Props(new CodebaseAnalyzeAggregatorActor) final case class AnalyzeDirectory(path: String) final case class Complete(result: Try[SourceCodeInfo]) final case object Timeout final case class Report(codebaseInfo: CodebaseInfo) } class CodebaseAnalyzeAggregatorActor extends Actor with ActorLogging with DirectoryScanner with ReportFormatter { var controller: ActorRef = _ var currentPath: String = _ var beginTime: Date = _ var fileCount = 0 var completeCount = 0 var failCount = 0 var result: CodebaseInfo = CodebaseInfo.empty var timeoutTimer: Cancellable = _ var router: Router = { val routees = Vector.fill(8) { val r = context.actorOf(SourceCodeAnalyzerActor.props()) context watch r ActorRefRoutee(r) } Router(RoundRobinRoutingLogic(), routees) } override def receive: Receive = { case AnalyzeDirectory(path) => { controller = sender() currentPath = path beginTime = BenchmarkUtil.recordStart(s"analyze folder $currentPath") foreachFile(path, PresetFilters.knownFileTypes, PresetFilters.ignoreFolders) { file => fileCount += 1 router.route(NewFile(file.getAbsolutePath), context.self) } import context.dispatcher timeoutTimer = context.system.scheduler.scheduleOnce((fileCount / 1000).seconds, context.self, Timeout) } case Complete(Success(sourceCodeInfo: SourceCodeInfo)) => { completeCount += 1 result = result + sourceCodeInfo finishIfAllComplete() } case Complete(Failure(exception)) => { completeCount += 1 failCount += 1 log.warning("processing file failed {}", exception) finishIfAllComplete() } case Timeout => { println(s"${result.totalFileNums} of $fileCount files processed before timeout") controller ! Report(result) BenchmarkUtil.recordElapse(s"analyze folder $currentPath", beginTime) } case Terminated(a) => router = router.removeRoutee(a) val r = context.actorOf(Props[SourceCodeAnalyzerActor]) context watch r router = router.addRoutee(r) case x@_ => log.error(s"receive unknown message $x") } def finishIfAllComplete(): Unit = { if (completeCount == fileCount) { timeoutTimer.cancel() controller ! Report(result) BenchmarkUtil.recordElapse(s"analyze folder $currentPath", beginTime) context.stop(self) } } }
Example 42
Source File: CodebaseAnalyzerStreamApp.scala From CodeAnalyzerTutorial with Apache License 2.0 | 5 votes |
package tutor import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl._ import com.typesafe.scalalogging.StrictLogging import tutor.utils.BenchmarkUtil import scala.collection.mutable.ArrayBuffer import scala.concurrent.Future import scala.util.{Failure, Success} object CodebaseAnalyzerStreamApp extends App with DirectoryScanner with SourceCodeAnalyzer with ReportFormatter with StrictLogging { implicit val system = ActorSystem("CodebaseAnalyzer") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val path = args(0) val beginTime = BenchmarkUtil.recordStart(s"analyze $path with akka stream") val files = scan(path, PresetFilters.knownFileTypes, PresetFilters.ignoreFolders).iterator var errorProcessingFiles: ArrayBuffer[Throwable] = ArrayBuffer.empty val done = Source.fromIterator(() => files).mapAsync(8)(path => Future { processFile(path) }).fold(CodebaseInfo.empty) { (acc, trySourceCodeInfo) => trySourceCodeInfo match { case Success(sourceCodeInfo) => acc + sourceCodeInfo case Failure(e) => { errorProcessingFiles += e acc } } }.runForeach(codebaseInfo => { println(format(codebaseInfo)) println(s"there are ${errorProcessingFiles.size} files failed to process.") }) done.onComplete { _ => BenchmarkUtil.recordElapse(s"analyze $path with akka stream", beginTime) system.terminate() } }
Example 43
Source File: ActiveMqTestSpec.scala From reactive-activemq with Apache License 2.0 | 5 votes |
package akka.stream.integration package activemq import akka.NotUsed import akka.actor.ActorRef import akka.stream.integration.PersonDomain.Person import akka.stream.scaladsl.{ Flow, Keep } import akka.stream.testkit.scaladsl.{ TestSink, TestSource } import akka.stream.testkit.{ TestPublisher, TestSubscriber } import akka.testkit.TestActor.AutoPilot import akka.testkit.TestProbe import JsonCamelMessageExtractor._ import JsonCamelMessageBuilder._ import scala.util.{ Failure, Success, Try } implicit def function1ToAutoPilot[S, T](f: S => T): AutoPilot = new AutoPilot { override def run(sender: ActorRef, msg: Any): AutoPilot = msg match { case s: S => val tryT: Try[T] = Try(f(s)) tryT match { case Success(t) => sender ! t function1ToAutoPilot(f) case Failure(f) => fail(s"Failed to apply supplied function to received message: $s", f) } case _ => fail(s"Received message is not of the required type: $msg") } } }
Example 44
Source File: AppRunnerSpec.scala From ScalaStan with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.scalastan.examples import org.scalatest.FunSpec import scala.util.{Failure, Success, Try} class AppRunnerSpec(app: App) extends FunSpec { private lazy val description = app.getClass.getSimpleName.stripSuffix("$") describe(description) { it("can run the app") { Try(app.main(Array.empty)) match { case Success(_) => () case Failure(t) => t.printStackTrace() fail(t) } } } }
Example 45
Source File: ArtifactStoreTestUtil.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.database.test.behavior import common.TestUtils import scala.util.{Failure, Success, Try} object ArtifactStoreTestUtil { def storeAvailable(storeAvailableCheck: Try[Any]): Boolean = { storeAvailableCheck match { case Success(_) => true case Failure(x) => //If running on master on main repo build tests MUST be run //For non main repo runs like in fork or for PR its fine for test //to be cancelled if (TestUtils.isBuildingOnMainRepo) throw x else false } } }
Example 46
Source File: KafkaProducerConnector.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.connector.kafka import akka.actor.ActorSystem import akka.pattern.after import org.apache.kafka.clients.producer._ import org.apache.kafka.common.errors._ import org.apache.kafka.common.serialization.StringSerializer import pureconfig._ import pureconfig.generic.auto._ import org.apache.openwhisk.common.{Counter, Logging, TransactionId} import org.apache.openwhisk.connector.kafka.KafkaConfiguration._ import org.apache.openwhisk.core.ConfigKeys import org.apache.openwhisk.core.connector.{Message, MessageProducer} import org.apache.openwhisk.core.entity.{ByteSize, UUIDs} import org.apache.openwhisk.utils.Exceptions import scala.collection.JavaConverters._ import scala.concurrent.duration._ import scala.concurrent.{blocking, ExecutionContext, Future, Promise} import scala.util.{Failure, Success} class KafkaProducerConnector( kafkahosts: String, id: String = UUIDs.randomUUID().toString, maxRequestSize: Option[ByteSize] = None)(implicit logging: Logging, actorSystem: ActorSystem) extends MessageProducer with Exceptions { implicit val ec: ExecutionContext = actorSystem.dispatcher private val gracefulWaitTime = 100.milliseconds override def sentCount(): Long = sentCounter.cur override def close(): Unit = { logging.info(this, "closing producer") producer.close() } private val sentCounter = new Counter() private def createProducer(): KafkaProducer[String, String] = { val config = Map(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> kafkahosts) ++ configMapToKafkaConfig(loadConfigOrThrow[Map[String, String]](ConfigKeys.kafkaCommon)) ++ configMapToKafkaConfig(loadConfigOrThrow[Map[String, String]](ConfigKeys.kafkaProducer)) ++ (maxRequestSize map { max => Map("max.request.size" -> max.size.toString) } getOrElse Map.empty) verifyConfig(config, ProducerConfig.configNames().asScala.toSet) tryAndThrow("creating producer")(new KafkaProducer(config, new StringSerializer, new StringSerializer)) } private def recreateProducer(): Unit = { logging.info(this, s"recreating producer") tryAndSwallow("closing old producer")(producer.close()) logging.info(this, s"old producer closed") producer = createProducer() } @volatile private var producer = createProducer() }
Example 47
Source File: KafkaMessagingProvider.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.connector.kafka import java.util.Properties import akka.actor.ActorSystem import org.apache.kafka.clients.admin.{AdminClient, AdminClientConfig, NewTopic} import org.apache.kafka.common.errors.{RetriableException, TopicExistsException} import pureconfig._ import pureconfig.generic.auto._ import org.apache.openwhisk.common.{CausedBy, Logging} import org.apache.openwhisk.core.{ConfigKeys, WhiskConfig} import org.apache.openwhisk.core.connector.{MessageConsumer, MessageProducer, MessagingProvider} import org.apache.openwhisk.core.entity.ByteSize import scala.collection.JavaConverters._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} case class KafkaConfig(replicationFactor: Short, consumerLagCheckInterval: FiniteDuration) def verifyConfig(config: Map[String, String], validKeys: Set[String])(implicit logging: Logging): Boolean = { val passedKeys = config.keySet val knownKeys = validKeys intersect passedKeys val unknownKeys = passedKeys -- knownKeys if (unknownKeys.nonEmpty) { logging.warn(this, s"potential misconfiguration, unknown settings: ${unknownKeys.mkString(",")}") false } else { true } } }
Example 48
Source File: PoolingRestClient.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.http import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling._ import akka.http.scaladsl.model._ import akka.http.scaladsl.settings.ConnectionPoolSettings import akka.http.scaladsl.unmarshalling._ import akka.stream.{ActorMaterializer, OverflowStrategy, QueueOfferResult} import akka.stream.scaladsl.{Flow, _} import spray.json._ import scala.concurrent.{ExecutionContext, Future, Promise} import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} def requestJson[T: RootJsonReader](futureRequest: Future[HttpRequest]): Future[Either[StatusCode, T]] = request(futureRequest).flatMap { response => if (response.status.isSuccess) { Unmarshal(response.entity.withoutSizeLimit).to[T].map(Right.apply) } else { Unmarshal(response.entity).to[String].flatMap { body => val statusCode = response.status val reason = if (body.nonEmpty) s"${statusCode.reason} (details: $body)" else statusCode.reason val customStatusCode = StatusCodes .custom(intValue = statusCode.intValue, reason = reason, defaultMessage = statusCode.defaultMessage) // This is important, as it drains the entity stream. // Otherwise the connection stays open and the pool dries up. response.discardEntityBytes().future.map(_ => Left(customStatusCode)) } } } def shutdown(): Future[Unit] = Future.successful(materializer.shutdown()) } object PoolingRestClient { def mkRequest(method: HttpMethod, uri: Uri, body: Future[MessageEntity] = Future.successful(HttpEntity.Empty), headers: List[HttpHeader] = List.empty)(implicit ec: ExecutionContext): Future[HttpRequest] = { body.map { b => HttpRequest(method, uri, headers, b) } } def mkJsonRequest(method: HttpMethod, uri: Uri, body: JsValue, headers: List[HttpHeader] = List.empty)( implicit ec: ExecutionContext): Future[HttpRequest] = { val b = Marshal(body).to[MessageEntity] mkRequest(method, uri, b, headers) } }
Example 49
Source File: Scheduler.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.common import scala.concurrent.Future import scala.concurrent.duration._ import scala.util.Failure import scala.util.Success import scala.util.Try import akka.actor.Actor import akka.actor.ActorSystem import akka.actor.Cancellable import akka.actor.Props def scheduleWaitAtLeast(interval: FiniteDuration, initialDelay: FiniteDuration = Duration.Zero, name: String = "Scheduler")(f: () => Future[Any])(implicit system: ActorSystem, logging: Logging, transid: TransactionId = TransactionId.unknown) = { require(interval > Duration.Zero) system.actorOf(Props(new Worker(initialDelay, interval, true, name, f))) } }
Example 50
Source File: ConcurrencyLimit.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.entity import com.typesafe.config.ConfigFactory import org.apache.openwhisk.core.ConfigKeys import pureconfig._ import pureconfig.generic.auto._ import scala.util.Failure import scala.util.Success import scala.util.Try import spray.json._ case class ConcurrencyLimitConfig(min: Int, max: Int, std: Int) @throws[IllegalArgumentException] protected[core] def apply(concurrency: Int): ConcurrencyLimit = { require(concurrency >= MIN_CONCURRENT, s"concurrency $concurrency below allowed threshold of $MIN_CONCURRENT") require(concurrency <= MAX_CONCURRENT, s"concurrency $concurrency exceeds allowed threshold of $MAX_CONCURRENT") new ConcurrencyLimit(concurrency) } override protected[core] implicit val serdes = new RootJsonFormat[ConcurrencyLimit] { def write(m: ConcurrencyLimit) = JsNumber(m.maxConcurrent) def read(value: JsValue) = { Try { val JsNumber(c) = value require(c.isWhole, "concurrency limit must be whole number") ConcurrencyLimit(c.toInt) } match { case Success(limit) => limit case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e) case Failure(e: Throwable) => deserializationError("concurrency limit malformed", e) } } } }
Example 51
Source File: LogLimit.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.entity import pureconfig._ import pureconfig.generic.auto._ import scala.language.postfixOps import scala.util.Failure import scala.util.Success import scala.util.Try import spray.json._ import org.apache.openwhisk.core.ConfigKeys import org.apache.openwhisk.core.entity.size._ case class LogLimitConfig(min: ByteSize, max: ByteSize, std: ByteSize) @throws[IllegalArgumentException] protected[core] def apply(megabytes: ByteSize): LogLimit = { require(megabytes >= MIN_LOGSIZE, s"log size $megabytes below allowed threshold of $MIN_LOGSIZE") require(megabytes <= MAX_LOGSIZE, s"log size $megabytes exceeds allowed threshold of $MAX_LOGSIZE") new LogLimit(megabytes.toMB.toInt) } override protected[core] implicit val serdes = new RootJsonFormat[LogLimit] { def write(m: LogLimit) = JsNumber(m.megabytes) def read(value: JsValue) = Try { val JsNumber(mb) = value require(mb.isWhole, "log limit must be whole number") LogLimit(mb.intValue MB) } match { case Success(limit) => limit case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e) case Failure(e: Throwable) => deserializationError("log limit malformed", e) } } }
Example 52
Source File: ActivationId.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.entity import spray.json.DefaultJsonProtocol.StringJsonFormat import spray.json._ import org.apache.openwhisk.http.Messages import org.apache.openwhisk.core.entity.size._ import scala.util.{Failure, Success, Try} protected[core] def generate(): ActivationId = new ActivationId(UUIDs.randomUUID().toString.filterNot(_ == '-')) protected[core] implicit val serdes: RootJsonFormat[ActivationId] = new RootJsonFormat[ActivationId] { def write(d: ActivationId) = JsString(d.toString) def read(value: JsValue): ActivationId = { val parsed = value match { case JsString(s) => ActivationId.parse(s) case JsNumber(n) => ActivationId.parse(n.toString) case _ => Failure(DeserializationException(Messages.activationIdIllegal)) } parsed match { case Success(aid) => aid case Failure(t: IllegalArgumentException) => deserializationError(t.getMessage) case Failure(_) => deserializationError(Messages.activationIdIllegal) } } } }
Example 53
Source File: TimeLimit.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.entity import pureconfig._ import pureconfig.generic.auto._ import scala.concurrent.duration._ import scala.util.Failure import scala.util.Success import scala.util.Try import spray.json.JsNumber import spray.json.JsValue import spray.json.RootJsonFormat import spray.json.deserializationError import org.apache.openwhisk.core.ConfigKeys @throws[IllegalArgumentException] protected[core] def apply(duration: FiniteDuration): TimeLimit = { require(duration != null, s"duration undefined") require( duration >= MIN_DURATION, s"duration ${duration.toMillis} milliseconds below allowed threshold of ${MIN_DURATION.toMillis} milliseconds") require( duration <= MAX_DURATION, s"duration ${duration.toMillis} milliseconds exceeds allowed threshold of ${MAX_DURATION.toMillis} milliseconds") new TimeLimit(duration) } override protected[core] implicit val serdes = new RootJsonFormat[TimeLimit] { def write(t: TimeLimit) = JsNumber(t.millis) def read(value: JsValue) = Try { val JsNumber(ms) = value require(ms.isWhole, "time limit must be whole number") TimeLimit(Duration(ms.intValue, MILLISECONDS)) } match { case Success(limit) => limit case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e) case Failure(e: Throwable) => deserializationError("time limit malformed", e) } } }
Example 54
Source File: MemoryLimit.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.entity import scala.language.postfixOps import scala.util.Failure import scala.util.Success import scala.util.Try import spray.json._ import org.apache.openwhisk.core.entity.size._ import org.apache.openwhisk.core.ConfigKeys import pureconfig._ import pureconfig.generic.auto._ case class MemoryLimitConfig(min: ByteSize, max: ByteSize, std: ByteSize) @throws[IllegalArgumentException] protected[core] def apply(megabytes: ByteSize): MemoryLimit = { require(megabytes >= MIN_MEMORY, s"memory $megabytes below allowed threshold of $MIN_MEMORY") require(megabytes <= MAX_MEMORY, s"memory $megabytes exceeds allowed threshold of $MAX_MEMORY") new MemoryLimit(megabytes.toMB.toInt) } override protected[core] implicit val serdes = new RootJsonFormat[MemoryLimit] { def write(m: MemoryLimit) = JsNumber(m.megabytes) def read(value: JsValue) = Try { val JsNumber(mb) = value require(mb.isWhole, "memory limit must be whole number") MemoryLimit(mb.intValue MB) } match { case Success(limit) => limit case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e) case Failure(e: Throwable) => deserializationError("memory limit malformed", e) } } }
Example 55
Source File: MessagingActiveAck.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.ack import org.apache.kafka.common.errors.RecordTooLargeException import org.apache.openwhisk.common.{Logging, TransactionId} import org.apache.openwhisk.core.connector.{AcknowledegmentMessage, EventMessage, MessageProducer} import org.apache.openwhisk.core.entity._ import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} class MessagingActiveAck(producer: MessageProducer, instance: InstanceId, eventSender: Option[EventSender])( implicit logging: Logging, ec: ExecutionContext) extends ActiveAck { override def apply(tid: TransactionId, activationResult: WhiskActivation, blockingInvoke: Boolean, controllerInstance: ControllerInstanceId, userId: UUID, acknowledegment: AcknowledegmentMessage): Future[Any] = { implicit val transid: TransactionId = tid def send(msg: AcknowledegmentMessage, recovery: Boolean = false) = { producer.send(topic = "completed" + controllerInstance.asString, msg).andThen { case Success(_) => val info = if (recovery) s"recovery ${msg.messageType}" else msg.messageType logging.info(this, s"posted $info of activation ${acknowledegment.activationId}") } } // UserMetrics are sent, when the slot is free again. This ensures, that all metrics are sent. if (acknowledegment.isSlotFree.nonEmpty) { eventSender.foreach { s => EventMessage.from(activationResult, instance.source, userId) match { case Success(msg) => s.send(msg) case Failure(t) => logging.error(this, s"activation event was not sent: $t") } } } // An acknowledgement containing the result is only needed for blocking invokes in order to further the // continuation. A result message for a non-blocking activation is not actually registered in the load balancer // and the container proxy should not send such an acknowlegement unless it's a blocking request. Here the code // is defensive and will shrink all non-blocking acknowledegments. send(if (blockingInvoke) acknowledegment else acknowledegment.shrink).recoverWith { case t if t.getCause.isInstanceOf[RecordTooLargeException] => send(acknowledegment.shrink, recovery = true) } } }
Example 56
Source File: RemoteCacheInvalidation.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.database import java.nio.charset.StandardCharsets import scala.concurrent.Future import scala.concurrent.duration.DurationInt import scala.util.Failure import scala.util.Success import scala.util.Try import akka.actor.ActorSystem import akka.actor.Props import spray.json._ import org.apache.openwhisk.common.Logging import org.apache.openwhisk.core.WhiskConfig import org.apache.openwhisk.core.connector.Message import org.apache.openwhisk.core.connector.MessageFeed import org.apache.openwhisk.core.connector.MessagingProvider import org.apache.openwhisk.core.entity.CacheKey import org.apache.openwhisk.core.entity.ControllerInstanceId import org.apache.openwhisk.core.entity.WhiskAction import org.apache.openwhisk.core.entity.WhiskActionMetaData import org.apache.openwhisk.core.entity.WhiskPackage import org.apache.openwhisk.core.entity.WhiskRule import org.apache.openwhisk.core.entity.WhiskTrigger import org.apache.openwhisk.spi.SpiLoader case class CacheInvalidationMessage(key: CacheKey, instanceId: String) extends Message { override def serialize = CacheInvalidationMessage.serdes.write(this).compactPrint } object CacheInvalidationMessage extends DefaultJsonProtocol { def parse(msg: String) = Try(serdes.read(msg.parseJson)) implicit val serdes = jsonFormat(CacheInvalidationMessage.apply _, "key", "instanceId") } class RemoteCacheInvalidation(config: WhiskConfig, component: String, instance: ControllerInstanceId)( implicit logging: Logging, as: ActorSystem) { import RemoteCacheInvalidation._ implicit private val ec = as.dispatchers.lookup("dispatchers.kafka-dispatcher") private val instanceId = s"$component${instance.asString}" private val msgProvider = SpiLoader.get[MessagingProvider] private val cacheInvalidationConsumer = msgProvider.getConsumer(config, s"$cacheInvalidationTopic$instanceId", cacheInvalidationTopic, maxPeek = 128) private val cacheInvalidationProducer = msgProvider.getProducer(config) def notifyOtherInstancesAboutInvalidation(key: CacheKey): Future[Unit] = { cacheInvalidationProducer.send(cacheInvalidationTopic, CacheInvalidationMessage(key, instanceId)).map(_ => ()) } private val invalidationFeed = as.actorOf(Props { new MessageFeed( "cacheInvalidation", logging, cacheInvalidationConsumer, cacheInvalidationConsumer.maxPeek, 1.second, removeFromLocalCache) }) def invalidateWhiskActionMetaData(key: CacheKey) = WhiskActionMetaData.removeId(key) private def removeFromLocalCache(bytes: Array[Byte]): Future[Unit] = Future { val raw = new String(bytes, StandardCharsets.UTF_8) CacheInvalidationMessage.parse(raw) match { case Success(msg: CacheInvalidationMessage) => { if (msg.instanceId != instanceId) { WhiskActionMetaData.removeId(msg.key) WhiskAction.removeId(msg.key) WhiskPackage.removeId(msg.key) WhiskRule.removeId(msg.key) WhiskTrigger.removeId(msg.key) } } case Failure(t) => logging.error(this, s"failed processing message: $raw with $t") } invalidationFeed ! MessageFeed.Processed } } object RemoteCacheInvalidation { val cacheInvalidationTopic = "cacheInvalidation" }
Example 57
Source File: WhiskChangeEventObserver.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.database.cosmosdb.cache import akka.Done import com.azure.data.cosmos.CosmosItemProperties import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext import com.google.common.base.Throwables import kamon.metric.MeasurementUnit import org.apache.openwhisk.common.{LogMarkerToken, Logging, MetricEmitter} import org.apache.openwhisk.core.database.CacheInvalidationMessage import org.apache.openwhisk.core.database.cosmosdb.CosmosDBConstants import org.apache.openwhisk.core.database.cosmosdb.CosmosDBUtil.unescapeId import org.apache.openwhisk.core.entity.CacheKey import scala.collection.concurrent.TrieMap import scala.collection.immutable.Seq import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} class WhiskChangeEventObserver(config: InvalidatorConfig, eventProducer: EventProducer)(implicit ec: ExecutionContext, log: Logging) extends ChangeFeedObserver { import WhiskChangeEventObserver._ override def process(context: ChangeFeedObserverContext, docs: Seq[CosmosItemProperties]): Future[Done] = { //Each observer is called from a pool managed by CosmosDB ChangeFeedProcessor //So its fine to have a blocking wait. If this fails then batch would be reread and //retried thus ensuring at-least-once semantics val f = eventProducer.send(processDocs(docs, config)) f.andThen { case Success(_) => MetricEmitter.emitCounterMetric(feedCounter, docs.size) recordLag(context, docs.last) case Failure(t) => log.warn(this, "Error occurred while sending cache invalidation message " + Throwables.getStackTraceAsString(t)) } } } trait EventProducer { def send(msg: Seq[String]): Future[Done] } object WhiskChangeEventObserver { val instanceId = "cache-invalidator" private val feedCounter = LogMarkerToken("cosmosdb", "change_feed", "count", tags = Map("collection" -> "whisks"))(MeasurementUnit.none) private val lags = new TrieMap[String, LogMarkerToken] def recordLag(context: ChangeFeedObserverContext, lastDoc: CosmosItemProperties): Unit = { val sessionToken = context.getFeedResponse.sessionToken() val lsnRef = lastDoc.get("_lsn") require(lsnRef != null, s"Non lsn defined in document $lastDoc") val lsn = lsnRef.toString.toLong val sessionLsn = getSessionLsn(sessionToken) val lag = sessionLsn - lsn val partitionKey = context.getPartitionKeyRangeId val gaugeToken = lags.getOrElseUpdate(partitionKey, createLagToken(partitionKey)) MetricEmitter.emitGaugeMetric(gaugeToken, lag) } private def createLagToken(partitionKey: String) = { LogMarkerToken("cosmosdb", "change_feed", "lag", tags = Map("collection" -> "whisks", "pk" -> partitionKey))( MeasurementUnit.none) } def getSessionLsn(token: String): Long = { // Session Token can be in two formats. Either {PartitionKeyRangeId}:{LSN} // or {PartitionKeyRangeId}:{Version}#{GlobalLSN} // See https://github.com/Azure/azure-documentdb-changefeedprocessor-dotnet/pull/113/files#diff-54cbd8ddcc33cab4120c8af04869f881 val parsedSessionToken = token.substring(token.indexOf(":") + 1) val segments = parsedSessionToken.split("#") val lsn = if (segments.size < 2) segments(0) else segments(1) lsn.toLong } def processDocs(docs: Seq[CosmosItemProperties], config: InvalidatorConfig)(implicit log: Logging): Seq[String] = { docs .filter { doc => val cid = Option(doc.getString(CosmosDBConstants.clusterId)) val currentCid = config.clusterId //only if current clusterId is configured do a check currentCid match { case Some(_) => cid != currentCid case None => true } } .map { doc => val id = unescapeId(doc.id()) log.info(this, s"Changed doc [$id]") val event = CacheInvalidationMessage(CacheKey(id), instanceId) event.serialize } } }
Example 58
Source File: CacheInvalidator.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.database.cosmosdb.cache import akka.Done import akka.actor.{ActorSystem, CoordinatedShutdown} import akka.kafka.ProducerSettings import akka.stream.ActorMaterializer import com.google.common.base.Throwables import com.typesafe.config.Config import org.apache.kafka.common.serialization.StringSerializer import org.apache.openwhisk.common.Logging import org.apache.openwhisk.core.database.RemoteCacheInvalidation.cacheInvalidationTopic import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} object CacheInvalidator { val instanceId = "cache-invalidator" val whisksCollection = "whisks" def start( globalConfig: Config)(implicit system: ActorSystem, materializer: ActorMaterializer, log: Logging): Future[Done] = { implicit val ec: ExecutionContext = system.dispatcher val config = CacheInvalidatorConfig(globalConfig) val producer = KafkaEventProducer( kafkaProducerSettings(defaultProducerConfig(globalConfig)), cacheInvalidationTopic, config.eventProducerConfig) val observer = new WhiskChangeEventObserver(config.invalidatorConfig, producer) val feedConsumer = new ChangeFeedConsumer(whisksCollection, config, observer) feedConsumer.isStarted.andThen { case Success(_) => registerShutdownTasks(system, feedConsumer, producer) log.info(this, s"Started the Cache invalidator service. ClusterId [${config.invalidatorConfig.clusterId}]") case Failure(t) => log.error(this, "Error occurred while starting the Consumer" + Throwables.getStackTraceAsString(t)) } } private def registerShutdownTasks(system: ActorSystem, feedConsumer: ChangeFeedConsumer, producer: KafkaEventProducer)(implicit ec: ExecutionContext, log: Logging): Unit = { CoordinatedShutdown(system).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "closeFeedListeners") { () => feedConsumer .close() .flatMap { _ => producer.close().andThen { case Success(_) => log.info(this, "Kafka producer successfully shutdown") } } } } def kafkaProducerSettings(config: Config): ProducerSettings[String, String] = ProducerSettings(config, new StringSerializer, new StringSerializer) def defaultProducerConfig(globalConfig: Config): Config = globalConfig.getConfig("akka.kafka.producer") }
Example 59
Source File: HTMLReportGenerator.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.reportGenerator import java.io.{BufferedWriter, File, FileWriter} import org.fusesource.scalate.{TemplateEngine, TemplateSource} import scala.io.Source import scala.util.{Failure, Success, Try} class HTMLReportGenerator extends ReportGenerator { val scalateEngine = new TemplateEngine def getContent(reportEntries: Seq[ReportEntry]) : Try[String] = Try { if (reportEntries.size==0) { throw new IllegalArgumentException("Cannot generate report with 0 reportEntries.") } val templateText = Source.fromInputStream(getClass.getResourceAsStream("/report/index.html")).mkString scalateEngine.escapeMarkup = false val regressionCount :Seq[Int] = reportEntries.flatMap { reportEntry => { reportEntry.requestReportEntries.map { requestReportEntry => { requestReportEntry.reqMessages.size } } } } val renderedContent = scalateEngine.layout(TemplateSource.fromText("/com/ebay/n/regression/text.ssp", templateText), Map("reportEntries" -> reportEntries, "regressionCount" -> regressionCount.sum)) renderedContent } def writeAndGetFile(content: String, reportFilePath: String) : Try[File] = Try { val outputFile = new File(reportFilePath) val bw = new BufferedWriter(new FileWriter(outputFile)) bw.write(content) bw.close() outputFile } override def generate(reportEntries: Seq[ReportEntry], reportFilePath: String): Try[File] = Try { getContent(reportEntries).flatMap { content => writeAndGetFile(content, reportFilePath) } match { case Success(file) => file case Failure(t) => throw t } } }
Example 60
Source File: RecordWorkflow.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.workflow import org.ebayopensource.regression.internal.datastore.BaseDataStore import org.ebayopensource.regression.internal.http.{BaseHttpClient, HTTPResponse} import org.ebayopensource.regression.internal.reader.{RequestEntry, TestStrategy} import org.ebayopensource.regression.testrun.TestRunException import org.slf4j.LoggerFactory import scala.util.{Failure, Success, Try} class RecordWorkflow(dataStore: BaseDataStore, httpClient: BaseHttpClient) { val logger = LoggerFactory.getLogger(classOf[RecordWorkflow]) def recordState(testIdentifier: String, strategy: TestStrategy): Try[Unit] = Try { strategy.requests.foreach { request => { logger.info(s"Started request ${request.requestName}") if (request.continuation.isDefined) { WorkflowTools.performContinuations(testIdentifier, strategy, request, httpClient).flatMap { httpResponses => recordResponse(testIdentifier, request, httpResponses, dataStore) } match { case Success(message) => message case Failure(exception) => throw exception } } else { WorkflowTools.performRequest(testIdentifier, strategy, request, httpClient).flatMap { httpResponse => recordResponse(testIdentifier, request, Seq(httpResponse), dataStore) } match { case Success(message) => message case Failure(exception) => throw exception } } } } } def recordResponse(testIdentifier: String, request: RequestEntry, httpResponses: Seq[HTTPResponse], dataStore: BaseDataStore): Try[String] = Try { (for { recordingEntries <- request.recorder.recordAndFilter(httpResponses) identifier <- dataStore.storeRequestRecording(testIdentifier, request.requestName, recordingEntries) awesome <- Try(s"Completed ${request.requestName} in test ${identifier} successfully") } yield awesome).recover { case e => throw new TestRunException(s"Could not record test: ${testIdentifier}. Failed in request: ${request.requestName}. Reason:= ${e}") } match { case Success(str) => str case Failure(t) => throw t } } }
Example 61
Source File: WorkflowTools.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.workflow import java.net.URI import org.ebayopensource.regression.internal.http.{BaseHttpClient, HTTPRequest, HTTPResponse} import org.ebayopensource.regression.internal.reader.{RequestEntry, TestStrategy} import scala.collection.mutable import scala.collection.mutable.ListBuffer import scala.util.{Failure, Success, Try} object WorkflowTools { def performRequest(testIdentifier: String, strategy: TestStrategy, request: RequestEntry, httpClient: BaseHttpClient): Try[HTTPResponse] = Try { // scalastyle:off val tryHTTPResponse = for { httpRequest <- convertRequestEntryToRequest(request, strategy) httpResponse <- httpClient.execute(httpRequest) } yield (httpResponse) // scalastyle:on tryHTTPResponse match { case Success(r) => r case Failure(t) => throw t } } def convertRequestEntryToRequest(request: RequestEntry, strategy: TestStrategy): Try[HTTPRequest] = Try { val body = if (request.requestBuilder.isEmpty) None else Some(request.requestBuilder.get.buildRequest(request.dataInput).get) HTTPRequest(new URI(strategy.service.baseURL.toString + request.path), strategy.headers ++ request.extraHeaders, request.method, body) } // scalastyle:off def performContinuations(testIdentifier: String, testStrategy: TestStrategy, requestEntry: RequestEntry, httpClient: BaseHttpClient): Try[Seq[HTTPResponse]] = Try { val queue = mutable.Queue[HTTPRequest]() val httpResponses = ListBuffer[HTTPResponse]() val firstRequest = convertRequestEntryToRequest(requestEntry, testStrategy) if (firstRequest.isFailure) throw firstRequest.failed.get queue.enqueue(firstRequest.get) while (!queue.isEmpty) { httpClient.execute(queue.dequeue()) match { case Success(httpResponse) => { if (requestEntry.progressPrinter.isDefined) requestEntry.progressPrinter.get.printProgress(httpResponse) httpResponses += httpResponse val continuationRequests = requestEntry.continuation.get.getContinuations(httpResponse) continuationRequests match { case Success(requests) => { requests.foreach(request => { queue.enqueue(request) }) } case Failure(t) => { throw t } } } case Failure(t) => { throw t } } } httpResponses } // scalastyle:on }
Example 62
Source File: SimpleHTTPJSONRecorder.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.components.recorder import org.ebayopensource.regression.internal.common.Util import org.ebayopensource.regression.internal.components.recorder.common.{Recorder, RecordingEntry, RequestRecordingEntry, RequestRecordingEntryTypes} import org.ebayopensource.regression.internal.http.HTTPResponse import scala.util.{Failure, Success, Try} class SimpleHTTPJSONRecorder extends Recorder { val mapper = Util.getMapper() override def record(responses: Seq[HTTPResponse]): Try[RequestRecordingEntry] = Try { val recordingEntries : Seq[RecordingEntry] = responses.flatMap { response => { getRecordingEntry(response) match { case Success(entries) => entries case Failure(t) => throw t } } } RequestRecordingEntry(recordingEntries) } def getRecordingEntry(resp: HTTPResponse): Try[Seq[RecordingEntry]] = Try { val body = resp.body var entries = Seq[RecordingEntry]() entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.STRING, resp.status.toString, "response status code") entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.STRING, resp.request.url.toString, "request url") (resp.request.body.isDefined) match { case true => entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.JSON, mapper.writeValueAsString(resp.request.body.get), "request body") case _ => } entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.STRING, resp.request.method.toString, "http method") resp.request.headers.toSeq.sortBy(_._1).foreach( entry => entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.STRING, s"${entry._1}=${entry._2}" ,"request header") ) resp.responseHeaders.toSeq.sortBy(_._1).foreach( entry => entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.STRING, s"${entry._1}=${entry._2}" ,"response header") ) (body.isDefined) match { case true => entries = entries :+ RecordingEntry(RequestRecordingEntryTypes.JSON, mapper.writeValueAsString(body.get), "response body") case _ => } entries } }
Example 63
Source File: Recorder.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.components.recorder.common import org.ebayopensource.regression.internal.http.HTTPResponse import scala.util.{Failure, Success, Try} abstract class Recorder { def recordAndFilter(responses: Seq[HTTPResponse]) : Try[RequestRecordingEntry] = Try { RequestRecordingEntry(record(responses) match { case Success(rre) => { rre.entries.map { recordingEntry => { if (Option(recordingEntry.data).isDefined) { recordingEntry } else { RecordingEntry(recordingEntry.entryType, "<value-was-not-resolved-please-check-recorder>", recordingEntry.description) } } } } case Failure(t) => throw t }) } protected def record(responses: Seq[HTTPResponse]) : Try[RequestRecordingEntry] }
Example 64
Source File: CustomJsonAssertTest.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.json import org.ebayopensource.regression.UnitSpec import scala.util.{Failure, Success, Try} )) match { case Success(t) => assert(false, "Expected JSON Excepion due to regression in value.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } "A custom JSON Asserter" should "be able to ignore regressions in JSON Arrays that have ONLY simple values" in { val json1 = """{"name":"eBay", "languages":["java","scala","python"]}""" val json2 = """{"name":"eBay", "languages":["java","scala","pythons","haskell"]}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, false, false)) match { case Success(t) => assert(true) case Failure(t) => assert(false, "Assert threw an exception which was not expected:= " + t.getMessage) } } "A custom JSON Asserter" should "be able to detect regressions in JSON Arrays that have ONLY simple values when compareJSONArrays is turned on" in { val json1 = """{"name":"eBay", "languages":["java","scala","python"]}""" val json2 = """{"name":"eBay", "languages":["java","scala","pythons","haskell"]}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, false, true)) match { case Success(t) => assert(false, "Expected an exception in array values comparision.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } "A custom JSON Asserter" should "default behavior should be to compare JSON Arrays" in { val json1 = """{"name":"eBay", "languages":["java","scala","python"]}""" val json2 = """{"name":"eBay", "languages":["java","scala","pythons","haskell"]}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, false)) match { case Success(t) => assert(false, "Expected an exception in array values comparision.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } "A custom JSON Asserter" should "be able to ignore ANY regressions in JSONArrays when compareJSONArrays is turned off " in { val json1 = """{"name":"eBay", "departments":[{"name":"core"},{"name":"n"}]}""" val json2 = """{"name":"eBay", "departments":[{"name":"core"},{"name":"npd"}]}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, true, false)) match { case Success(t) => assert(true) case Failure(t) => { assert(false, s"Should not have thrown exception for value regression. ${t}") } } } "A custom JSON Asserter" should "be able to detect deep level regressions in values" in { val json1 = """{"name":"eBay", "department":{"name":"npd","size":"50"}}""" val json2 = """{"name":"eBay", "department":{"name":"npd","size":"60"}}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, true)) match { case Success(t) => assert(false, "Expected an exception in values comparision.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } "A custom JSON Asserter" should "be able to detect deep level regressions in element names" in { val json1 = """{"name":"eBay", "department":{"name":"npd","size":"50"}}""" val json2 = """{"name":"eBay", "department":{"name":"npd","sizes":"60"}}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, false)) match { case Success(t) => assert(false, "Expected an exception in element name comparision.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } "A custom JSON Asserter" should "be able to detect extensions in JSON" in { val json1 = """{"name":"eBay", "department":{"name":"npd","size":"50"}}""" val json2 = """{"name":"eBay", "department":{"name":"npd","size":"50"}, "age":"20"}""" Try[Unit] (CustomJsonAssert.assertEquals(json1, json2, false)) match { case Success(t) => assert(false, "Expected an exception in element name comparision.") case Failure(t) => assert(t.isInstanceOf[AssertionError]) } } }
Example 65
Source File: YAMLTestStrategyReaderTest.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.reader import org.ebayopensource.regression.UnitSpec import scala.io.Source import scala.util.{Failure, Success} class YAMLTestStrategyReaderTest extends UnitSpec { "A reader" should "be able to read a valid strategy file with 1 request" in { val strategyContent = Source.fromInputStream(getClass.getResourceAsStream("/yaml/valid_strategy_simple_one_request.yaml")).mkString.replace("\t","") YAMLTestStrategyReader.read(strategyContent) match { case Success(t) => { assert(t.requests.size == 1) assert(t.headers.size>0) } case Failure(t) => assert(false, s"Strategy file was valid. Should not throw exception ${t.getMessage}") } } }
Example 66
Source File: SimpleHTTPJSONRecorderTest.scala From regressr with Apache License 2.0 | 5 votes |
package org.ebayopensource.regression.internal.components.recorder import java.net.URI import org.ebayopensource.regression.UnitSpec import org.ebayopensource.regression.internal.http.{HTTPRequest, HTTPResponse} import org.ebayopensource.regression.internal.reader.HttpMethods import scala.util.{Failure, Success} class SimpleHTTPJSONRecorderTest extends UnitSpec { "A simple http json recorder" should "generate recording entries when a GET Request is passed into it" in { val recorder = new SimpleHTTPJSONRecorder val re = recorder.recordAndFilter(Seq(HTTPResponse( HTTPRequest(new URI("http://www.ebay.com"), Map("header1" -> "value1"), HttpMethods.GET, None), 200, Some("""{"name":"value"}"""), Map("responseHeader1" -> "responseValue1")))) re match { case Success(t) => assert(t.entries.size>0) // case Failure(t) => assert(false, t) } } "A simple http json recorder" should "generate 7 recording entries when a POST Request is passed into it" in { val recorder = new SimpleHTTPJSONRecorder val re = recorder.recordAndFilter(Seq(HTTPResponse( HTTPRequest(new URI("http://www.ebay.com"), Map("header1" -> "value1"), HttpMethods.POST, Some("")), 200, Some("""{"name":"value"}"""), Map("responseHeader1" -> "responseValue1")))) re match { case Success(t) => assert(t.entries.size>0) // case Failure(t) => assert(false, t) } } }
Example 67
Source File: Transformer.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.runtime.frame
import java.util.UUID
import ml.combust.mleap.core.Model
import ml.combust.mleap.core.types.{NodeShape, StructField, StructType}
import ml.combust.mleap.runtime.function.{FieldSelector, Selector, UserDefinedFunction}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}
}
}
trait BaseTransformer extends Transformer {
val exec: UserDefinedFunction
val inputs: Seq[String] = inputSchema.fields.map(_.name)
val selectors: Seq[Selector] = inputs.map(FieldSelector)
}
trait SimpleTransformer extends BaseTransformer {
val output: String = outputSchema.fields.head.name
lazy val typedExec: UserDefinedFunction = exec.withInputs(inputSchema).withOutput(outputSchema)
override def transform[FB <: FrameBuilder[FB]](builder: FB): Try[FB] = {
builder.withColumn(output, selectors: _*)(typedExec)
}
}
trait MultiTransformer extends BaseTransformer {
val outputs: Seq[String] = outputSchema.fields.map(_.name)
lazy val typedExec: UserDefinedFunction = exec.withInputs(inputSchema).withOutput(outputSchema)
override def transform[FB <: FrameBuilder[FB]](builder: FB): Try[FB] = {
builder.withColumns(outputs, selectors: _*)(typedExec)
}
}
Example 68
Source File: RunServer.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.grpc.server import java.util.concurrent.{Executors, TimeUnit} import akka.Done import akka.actor.{ActorSystem, CoordinatedShutdown} import akka.stream.{ActorMaterializer, Materializer} import com.typesafe.config.Config import com.typesafe.scalalogging.Logger import io.grpc.ServerBuilder import ml.combust.mleap.executor.MleapExecutor import ml.combust.mleap.pb.MleapGrpc import scala.concurrent.{ExecutionContext, Future} import scala.language.existentials import scala.util.{Failure, Success, Try} class RunServer(config: Config) (implicit system: ActorSystem) { private val logger = Logger(classOf[RunServer]) private var coordinator: Option[CoordinatedShutdown] = None def run(): Unit = { Try { logger.info("Starting MLeap gRPC Server") val coordinator = CoordinatedShutdown(system) this.coordinator = Some(coordinator) implicit val materializer: Materializer = ActorMaterializer() val grpcServerConfig = new GrpcServerConfig(config.getConfig("default")) val mleapExecutor = MleapExecutor(system) val port: Int = config.getInt("port") val threads: Option[Int] = if (config.hasPath("threads")) Some(config.getInt("threads")) else None val threadCount = threads.getOrElse { Math.min(Math.max(Runtime.getRuntime.availableProcessors() * 4, 32), 64) } logger.info(s"Creating thread pool for server with size $threadCount") val grpcThreadPool = Executors.newFixedThreadPool(threadCount) implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(grpcThreadPool) coordinator.addTask(CoordinatedShutdown.PhaseServiceRequestsDone, "threadPoolShutdownNow") { () => Future { logger.info("Shutting down gRPC thread pool") grpcThreadPool.shutdown() grpcThreadPool.awaitTermination(5, TimeUnit.SECONDS) Done } } logger.info(s"Creating executor service") val grpcService: GrpcServer = new GrpcServer(mleapExecutor, grpcServerConfig) val builder = ServerBuilder.forPort(port) builder.intercept(new ErrorInterceptor) builder.addService(MleapGrpc.bindService(grpcService, ec)) val grpcServer = builder.build() logger.info(s"Starting server on port $port") grpcServer.start() coordinator.addTask(CoordinatedShutdown.PhaseServiceUnbind, "grpcServiceShutdown") { () => Future { logger.info("Shutting down gRPC") grpcServer.shutdown() grpcServer.awaitTermination(10, TimeUnit.SECONDS) Done }(ExecutionContext.global) } coordinator.addTask(CoordinatedShutdown.PhaseServiceStop, "grpcServiceShutdownNow") { () => Future { if (!grpcServer.isShutdown) { logger.info("Shutting down gRPC NOW!") grpcServer.shutdownNow() grpcServer.awaitTermination(5, TimeUnit.SECONDS) } Done }(ExecutionContext.global) } } match { case Success(_) => case Failure(err) => logger.error("Error encountered starting server", err) for (c <- this.coordinator) { c.run(CoordinatedShutdown.UnknownReason) } throw err } } }
Example 69
Source File: LocalTransformServiceActor.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.executor.service import akka.actor.{Actor, ActorRef, Props, Status, Terminated} import akka.stream.{ActorMaterializer, Materializer} import ml.combust.mleap.executor.repository.RepositoryBundleLoader import ml.combust.mleap.executor._ import ml.combust.mleap.executor.error.NotFoundException import scala.util.{Failure, Success, Try} object LocalTransformServiceActor { def props(loader: RepositoryBundleLoader, config: ExecutorConfig): Props = { Props(new LocalTransformServiceActor(loader, config)) } object Messages { case object Close } } class LocalTransformServiceActor(loader: RepositoryBundleLoader, config: ExecutorConfig) extends Actor { import LocalTransformServiceActor.Messages private implicit val materializer: Materializer = ActorMaterializer()(context.system) private var lookup: Map[String, ActorRef] = Map() private var modelNameLookup: Map[ActorRef, String] = Map() override def postStop(): Unit = { for (child <- context.children) { context.unwatch(child) context.stop(child) } } override def receive: Receive = { case request: TransformFrameRequest => handleModelRequest(request) case request: GetBundleMetaRequest => handleModelRequest(request) case request: GetModelRequest => handleModelRequest(request) case request: CreateFrameStreamRequest => handleModelRequest(request) case request: CreateRowStreamRequest => handleModelRequest(request) case request: GetRowStreamRequest => handleModelRequest(request) case request: CreateFrameFlowRequest => handleModelRequest(request) case request: GetFrameStreamRequest => handleModelRequest(request) case request: CreateRowFlowRequest => handleModelRequest(request) case request: UnloadModelRequest => handleModelRequest(request) case request: LoadModelRequest => loadModel(request) case Messages.Close => context.stop(self) case Terminated(actor) => terminated(actor) } def handleModelRequest(request: ModelRequest): Unit = { lookup.get(request.modelName) match { case Some(actor) => actor.tell(request, sender) case None => sender ! Status.Failure(new NotFoundException(s"no model with name ${request.modelName}")) } } def loadModel(request: LoadModelRequest): Unit = { Try(context.actorOf(BundleActor.props(request, loader, config), request.modelName)) match { case Success(actor) => lookup += (request.modelName -> actor) modelNameLookup += (actor -> request.modelName) context.watch(actor) actor.tell(request, sender) case Failure(err) => sender ! Status.Failure(err) } } private def terminated(ref: ActorRef): Unit = { val uri = modelNameLookup(ref) modelNameLookup -= ref lookup -= uri } }
Example 70
Source File: DefaultFrameWriter.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.avro import java.io.ByteArrayOutputStream import java.nio.charset.Charset import org.apache.avro.Schema import org.apache.avro.file.DataFileWriter import org.apache.avro.generic.{GenericData, GenericDatumWriter} import SchemaConverter._ import ml.combust.mleap.runtime.frame.LeapFrame import ml.combust.mleap.runtime.serialization.{BuiltinFormats, FrameWriter} import resource._ import scala.util.{Failure, Try} class DefaultFrameWriter[LF <: LeapFrame[LF]](frame: LF) extends FrameWriter { val valueConverter = ValueConverter() override def toBytes(charset: Charset = BuiltinFormats.charset): Try[Array[Byte]] = { (for(out <- managed(new ByteArrayOutputStream())) yield { val writers = frame.schema.fields.map(_.dataType).map(valueConverter.mleapToAvro) val avroSchema = frame.schema: Schema val record = new GenericData.Record(avroSchema) val datumWriter = new GenericDatumWriter[GenericData.Record](avroSchema) val writer = new DataFileWriter[GenericData.Record](datumWriter) writer.create(avroSchema, out) for(row <- frame.collect()) { var i = 0 for(writer <- writers) { record.put(i, writer(row.getRaw(i))) i = i + 1 } Try(writer.append(record)) match { case Failure(error) => error.printStackTrace() case _ => } } writer.close() out.toByteArray }).tried } }
Example 71
Source File: OneHotEncoderOp.scala From mleap with Apache License 2.0 | 5 votes |
package org.apache.spark.ml.bundle.ops.feature import ml.combust.bundle.BundleContext import ml.combust.bundle.dsl._ import ml.combust.bundle.op.OpModel import org.apache.spark.ml.attribute.{Attribute, BinaryAttribute, NominalAttribute, NumericAttribute} import org.apache.spark.ml.bundle._ import org.apache.spark.ml.feature.OneHotEncoderModel import org.apache.spark.sql.types.StructField import scala.util.{Failure, Try} object OneHotEncoderOp { def sizeForField(field: StructField): Int = { val attr = Attribute.fromStructField(field) (attr match { case nominal: NominalAttribute => if (nominal.values.isDefined) { Try(nominal.values.get.length) } else if (nominal.numValues.isDefined) { Try(nominal.numValues.get) } else { Failure(new RuntimeException(s"invalid nominal value for field ${field.name}")) } case binary: BinaryAttribute => Try(2) case _: NumericAttribute => Failure(new RuntimeException(s"invalid numeric attribute for field ${field.name}")) case _ => Failure(new RuntimeException(s"unsupported attribute for field ${field.name}")) // optimistic about unknown attributes }).get } } class OneHotEncoderOp extends SimpleSparkOp[OneHotEncoderModel] { override val Model: OpModel[SparkBundleContext, OneHotEncoderModel] = new OpModel[SparkBundleContext, OneHotEncoderModel] { override val klazz: Class[OneHotEncoderModel] = classOf[OneHotEncoderModel] override def opName: String = Bundle.BuiltinOps.feature.one_hot_encoder override def store(model: Model, obj: OneHotEncoderModel) (implicit context: BundleContext[SparkBundleContext]): Model = { assert(context.context.dataset.isDefined, BundleHelper.sampleDataframeMessage(klazz)) val df = context.context.dataset.get val categorySizes = obj.getInputCols.map { f ⇒ OneHotEncoderOp.sizeForField(df.schema(f)) } model.withValue("category_sizes", Value.intList(categorySizes)) .withValue("drop_last", Value.boolean(obj.getDropLast)) .withValue("handle_invalid", Value.string(obj.getHandleInvalid)) } override def load(model: Model) (implicit context: BundleContext[SparkBundleContext]): OneHotEncoderModel = { new OneHotEncoderModel(uid = "", categorySizes = model.value("category_sizes").getIntList.toArray) .setDropLast(model.value("drop_last").getBoolean) .setHandleInvalid(model.value("handle_invalid").getString) } } override def sparkLoad(uid: String, shape: NodeShape, model: OneHotEncoderModel): OneHotEncoderModel = { new OneHotEncoderModel(uid = uid, categorySizes = model.categorySizes) .setDropLast(model.getDropLast) .setHandleInvalid(model.getHandleInvalid) } override def sparkInputs(obj: OneHotEncoderModel): Seq[ParamSpec] = Seq(ParamSpec("input", obj.inputCols)) override def sparkOutputs(obj: OneHotEncoderModel): Seq[ParamSpec] = Seq(ParamSpec("output", obj.outputCols)) }
Example 72
Source File: ReverseStringIndexerOp.scala From mleap with Apache License 2.0 | 5 votes |
package org.apache.spark.ml.bundle.ops.feature import ml.combust.bundle.BundleContext import ml.combust.bundle.op.OpModel import ml.combust.bundle.dsl._ import ml.combust.mleap.core.types.{DataShape, ScalarShape} import org.apache.spark.ml.attribute.{Attribute, BinaryAttribute, NominalAttribute, NumericAttribute} import org.apache.spark.ml.bundle._ import org.apache.spark.ml.feature.IndexToString import org.apache.spark.sql.types.StructField import ml.combust.mleap.runtime.types.BundleTypeConverters._ import scala.util.{Failure, Try} object ReverseStringIndexerOp { def labelsForField(field: StructField): Array[String] = { val attr = Attribute.fromStructField(field) (attr match { case nominal: NominalAttribute => if (nominal.values.isDefined) { Try(nominal.values.get) } else { Failure(new RuntimeException(s"invalid nominal value for field ${field.name}")) } case _: BinaryAttribute => Failure(new RuntimeException(s"invalid binary attribute for field ${field.name}")) case _: NumericAttribute => Failure(new RuntimeException(s"invalid numeric attribute for field ${field.name}")) case _ => Failure(new RuntimeException(s"unsupported attribute for field ${field.name}")) // optimistic about unknown attributes }).get } } class ReverseStringIndexerOp extends SimpleSparkOp[IndexToString] { override val Model: OpModel[SparkBundleContext, IndexToString] = new OpModel[SparkBundleContext, IndexToString] { override val klazz: Class[IndexToString] = classOf[IndexToString] override def opName: String = Bundle.BuiltinOps.feature.reverse_string_indexer override def store(model: Model, obj: IndexToString) (implicit context: BundleContext[SparkBundleContext]): Model = { val labels = obj.get(obj.labels).getOrElse { assert(context.context.dataset.isDefined, BundleHelper.sampleDataframeMessage(klazz)) val df = context.context.dataset.get ReverseStringIndexerOp.labelsForField(df.schema(obj.getInputCol)) } model.withValue("labels", Value.stringList(labels)). withValue("input_shape", Value.dataShape(ScalarShape(false))) } override def load(model: Model) (implicit context: BundleContext[SparkBundleContext]): IndexToString = { model.getValue("input_shape").map(_.getDataShape: DataShape).foreach { shape => require(shape.isScalar, "cannot deserialize non-scalar input to Spark IndexToString model") } new IndexToString(uid = "").setLabels(model.value("labels").getStringList.toArray) } } override def sparkLoad(uid: String, shape: NodeShape, model: IndexToString): IndexToString = { new IndexToString(uid = uid).setLabels(model.getLabels) } override def sparkInputs(obj: IndexToString): Seq[ParamSpec] = { Seq("input" -> obj.inputCol) } override def sparkOutputs(obj: IndexToString): Seq[SimpleParamSpec] = { Seq("output" -> obj.outputCol) } }
Example 73
Source File: ErrorHandlingSpec.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.bundle.serializer import java.io.File import ml.combust.bundle.{BundleFile, BundleRegistry, TestUtil} import ml.combust.bundle.test.TestContext import ml.combust.bundle.test.ops._ import org.scalatest.FunSpec import ml.combust.bundle.test.TestSupport._ import resource._ import scala.util.{Failure, Random} case class UnknownTransformer() extends Transformer { override val uid: String = "haha" } class ErrorHandlingSpec extends FunSpec { implicit val testContext = TestContext(BundleRegistry("test-registry")) val randomCoefficients = (0 to 100000).map(v => Random.nextDouble()) val lr = LinearRegression(uid = "linear_regression_example", input = "input_field", output = "output_field", model = LinearModel(coefficients = randomCoefficients, intercept = 44.5)) val si = StringIndexer(uid = "string_indexer_example", input = "input_string", output = "output_index", model = StringIndexerModel(strings = Seq("hey", "there", "man"))) val pipeline = Pipeline(uid = "my_pipeline", PipelineModel(Seq(si, lr))) describe("with unknown op") { it("returns a failure") { val result = (for(bf <- managed(BundleFile(new File(TestUtil.baseDir, "bad-model.zip")))) yield { UnknownTransformer().writeBundle.save(bf) }).tried.flatMap(identity) assert(result.isFailure) result match { case Failure(error) => assert(error.isInstanceOf[NoSuchElementException]) assert(error.getMessage == "key not found: ml.combust.bundle.serializer.UnknownTransformer") case _ => } } } }
Example 74
Source File: ProtobufScoringController.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.springboot import java.util.concurrent.CompletionStage import akka.actor.ActorSystem import com.google.protobuf.ByteString import ml.combust.mleap.executor._ import ml.combust.mleap.pb.TransformStatus.STATUS_ERROR import ml.combust.mleap.pb.{BundleMeta, Mleap, Model, TransformFrameResponse} import ml.combust.mleap.runtime.serialization.{FrameReader, FrameWriter} import ml.combust.mleap.springboot.TypeConverters._ import org.apache.commons.lang3.exception.ExceptionUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation._ import scala.compat.java8.FutureConverters._ import scala.concurrent.Future import scala.util.{Failure, Success} @RestController @RequestMapping class ProtobufScoringController(@Autowired val actorSystem : ActorSystem, @Autowired val mleapExecutor: MleapExecutor) { private val executor = actorSystem.dispatcher @PostMapping(path = Array("/models"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) @ResponseStatus(HttpStatus.ACCEPTED) def loadModel(@RequestBody request: Mleap.LoadModelRequest, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int) : CompletionStage[Mleap.Model] = { mleapExecutor .loadModel(javaPbToExecutorLoadModelRequest(request))(timeout) .map(model => Model.toJavaProto(model))(executor).toJava } @DeleteMapping(path = Array("/models/{model_name}"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) def unloadModel(@PathVariable("model_name") modelName: String, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int): CompletionStage[Mleap.Model] = mleapExecutor .unloadModel(UnloadModelRequest(modelName))(timeout) .map(model => Model.toJavaProto(model))(executor).toJava @GetMapping(path = Array("/models/{model_name}"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) def getModel(@PathVariable("model_name") modelName: String, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int): CompletionStage[Mleap.Model] = mleapExecutor .getModel(GetModelRequest(modelName))(timeout) .map(model => Model.toJavaProto(model))(executor).toJava @GetMapping(path = Array("/models/{model_name}/meta"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) def getMeta(@PathVariable("model_name") modelName: String, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int) : CompletionStage[Mleap.BundleMeta] = mleapExecutor .getBundleMeta(GetBundleMetaRequest(modelName))(timeout) .map(meta => BundleMeta.toJavaProto(meta))(executor).toJava @PostMapping(path = Array("/models/transform"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) def transform(@RequestBody request: Mleap.TransformFrameRequest, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int) : CompletionStage[Mleap.TransformFrameResponse] = { FrameReader(request.getFormat).fromBytes(request.getFrame.toByteArray) match { case Success(frame) => mleapExecutor.transform(TransformFrameRequest(request.getModelName, frame, request.getOptions))(timeout) .mapAll { case Success(resp) => resp match { case Success(frame) => TransformFrameResponse(tag = request.getTag, frame = ByteString.copyFrom(FrameWriter(frame, request.getFormat).toBytes().get)) case Failure(ex) => handleTransformFailure(request.getTag, ex) } case Failure(ex) => handleTransformFailure(request.getTag, ex) }(executor) .map(response => TransformFrameResponse.toJavaProto(response))(executor).toJava case Failure(ex) => Future { TransformFrameResponse.toJavaProto(handleTransformFailure(request.getTag, ex)) }(executor).toJava } } private def handleTransformFailure(tag: Long, ex: Throwable): TransformFrameResponse = { ProtobufScoringController.logger.error("Transform error due to ", ex) TransformFrameResponse(tag = tag, status = STATUS_ERROR, error = ExceptionUtils.getMessage(ex), backtrace = ExceptionUtils.getStackTrace(ex)) } } object ProtobufScoringController { val logger = LoggerFactory.getLogger(classOf[ProtobufScoringController]) }
Example 75
Source File: LeapFrameScoringController.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.springboot import java.util.concurrent.CompletionStage import akka.actor.ActorSystem import ml.combust.mleap.executor.{MleapExecutor, TransformFrameRequest} import ml.combust.mleap.pb.ErrorTransformResponse import ml.combust.mleap.pb.TransformStatus.STATUS_ERROR import ml.combust.mleap.runtime.serialization.{BuiltinFormats, FrameReader, FrameWriter} import ml.combust.mleap.springboot.TypeConverters._ import org.apache.commons.lang3.exception.ExceptionUtils import org.json4s.jackson.JsonMethods import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation._ import scala.compat.java8.FutureConverters._ import scala.concurrent.Future import scala.util.{Failure, Success} import scalapb.json4s.{Parser, Printer} @RestController @RequestMapping class LeapFrameScoringController(@Autowired val actorSystem : ActorSystem, @Autowired val mleapExecutor: MleapExecutor, @Autowired val jsonPrinter: Printer, @Autowired val jsonParser: Parser) { private val executor = actorSystem.dispatcher @PostMapping(path = Array("/models/{model_name}/transform"), consumes = Array("application/json; charset=UTF-8"), produces = Array("application/json; charset=UTF-8")) def transformJson(@RequestBody body: Array[Byte], @PathVariable("model_name") modelName: String, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int) : CompletionStage[_] = { FrameReader(BuiltinFormats.json).fromBytes(body) match { case Success(frame) => mleapExecutor.transform(TransformFrameRequest(modelName, frame, None))(timeout) .mapAll { case Success(resp) => resp match { case Success(frame) => FrameWriter(frame, BuiltinFormats.json).toBytes().get case Failure(ex) => JsonMethods.compact(jsonPrinter.toJson(handleTransformFailure(ex))) } case Failure(ex) => JsonMethods.compact(jsonPrinter.toJson(handleTransformFailure(ex))) }(executor) .toJava case Failure(ex) => Future { JsonMethods.compact(jsonPrinter.toJson(handleTransformFailure(ex))) }(executor).toJava } } @PostMapping(path = Array("/models/{model_name}/transform"), consumes = Array("application/x-protobuf; charset=UTF-8"), produces = Array("application/x-protobuf; charset=UTF-8")) def transformProto(@RequestBody body: Array[Byte], @PathVariable("model_name") modelName: String, @RequestHeader(value = "timeout", defaultValue = "60000") timeout: Int) : CompletionStage[_] = { FrameReader(BuiltinFormats.binary).fromBytes(body) match { case Success(frame) => mleapExecutor.transform(TransformFrameRequest(modelName, frame, None))(timeout) .mapAll { case Success(resp) => resp match { case Success(frame) => FrameWriter(frame, BuiltinFormats.binary).toBytes().get case Failure(ex) => ErrorTransformResponse.toJavaProto(handleTransformFailure(ex)) } case Failure(ex) => ErrorTransformResponse.toJavaProto(handleTransformFailure(ex)) }(executor).toJava case Failure(ex) => Future { ErrorTransformResponse.toJavaProto(handleTransformFailure(ex)) }(executor).toJava } } private def handleTransformFailure(ex: Throwable): ErrorTransformResponse = { LeapFrameScoringController.logger.error("Transform error due to ", ex) ErrorTransformResponse(status = STATUS_ERROR, error = ExceptionUtils.getMessage(ex), backtrace = ExceptionUtils.getStackTrace(ex)) } } object LeapFrameScoringController { val logger = LoggerFactory.getLogger(classOf[LeapFrameScoringController]) }
Example 76
Source File: Environment.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.cli.configuration import java.net.URL import better.files.File import com.codacy.analysis.core.utils.Implicits._ import org.log4s.{Logger, getLogger} import scala.util.{Failure, Try} class Environment(variables: Map[String, String]) { private val logger: Logger = getLogger def codeDirectoryEnvironmentVariable(): Option[String] = { validate("Project directory", "environment variable", "CODACY_CODE")(variables.get("CODACY_CODE")) } def projectTokenArgument(projectTokenFromArguments: Option[String]): Option[String] = { validate("Project token", "argument", "--project-token")(projectTokenFromArguments) } def projectTokenEnvironmentVariable(): Option[String] = { validate("Project token", "environment variable", "CODACY_PROJECT_TOKEN")(variables.get("CODACY_PROJECT_TOKEN")) } def apiTokenArgument(apiTokenFromArguments: Option[String]): Option[String] = { validate("API token", "argument", "--api-token")(apiTokenFromArguments) } def apiTokenEnvironmentVariable(): Option[String] = { validate("API token", "environment variable", "CODACY_API_TOKEN")(variables.get("CODACY_API_TOKEN")) } def apiBaseUrlArgument(codacyApiBaseURLFromArguments: Option[String]): Option[String] = { val apiURL = validate("API base URL", "argument", "--codacy-api-base-url")(codacyApiBaseURLFromArguments) validateApiBaseUrl(apiURL) } def apiBaseUrlEnvironmentVariable(): Option[String] = { val apiURL = validate("API base URL", "environment variable", "CODACY_API_BASE_URL")(variables.get("CODACY_API_BASE_URL")) validateApiBaseUrl(apiURL) } def baseProjectDirectory(directory: Option[File]): File = directory.fold(codeDirectoryEnvironmentVariable().map(File(_)).getOrElse(File.currentWorkingDirectory))(dir => if (dir.isDirectory) dir else dir.parent) private def validateApiBaseUrl(apiURL: Option[String]): Option[String] = { apiURL.flatMap { url => Try(new URL(url)) match { case Failure(_) => val error = s"Invalid API base URL: $url" val help = if (!url.startsWith("http")) { " * Maybe you forgot the http:// or https:// ?" } logger.warn(s"$error\n$help") Option.empty[String] case _ => logger.info(s"Using API base URL $url") Option(url) } } } private def validate(name: String, paramType: String, param: String)(value: Option[String]): Option[String] = { value.ifEmpty(logger.info(s"$name not passed through $paramType `$param`")).flatMap { case t if t.trim.nonEmpty => logger.info(s"$name found in $paramType `$param`") Option(t.trim) case _ => logger.warn(s"$name passed through $paramType `$param` is empty") Option.empty[String] } } }
Example 77
Source File: MetricsToolExecutor.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.cli.analysis import java.nio.file.Path import better.files.File import com.codacy.analysis.core import com.codacy.analysis.core.model.FileMetrics import scala.util.{Failure, Success} object MetricsToolExecutor { import com.codacy.analysis.cli.analysis.AnalyseExecutor._ def reduceMetricsToolResultsByFile(metricsResults: Seq[MetricsToolExecutorResult]): Seq[MetricsToolExecutorResult] = { val (successfulMetricsResults, failedMetricsResults) = metricsResults.partition(_.analysisResults.isSuccess) successfulMetricsResults .groupBy(_.language) .values .flatMap { _.foldLeft(Option.empty[MetricsToolExecutorResult]) { case ( Some(metricsExecutorResAcc @ MetricsToolExecutorResult(_, _, Success(fileMetricsAcc))), metricsExecutorRes @ MetricsToolExecutorResult(_, _, Success(fileMetrics))) => val allFiles = metricsExecutorResAcc.files ++ metricsExecutorRes.files val reducedFileMetrics = reduceFileMetricsByFile(fileMetrics ++ fileMetricsAcc) Some(metricsExecutorResAcc.copy(files = allFiles, analysisResults = Success(reducedFileMetrics))) case (_, o) => Some(o) } }(collection.breakOut) ++ failedMetricsResults } private def reduceFileMetricsByFile(fileMetrics: Set[FileMetrics]): Set[FileMetrics] = { fileMetrics .groupBy(_.filename) .flatMap { case (filePath, fMetrics) => fMetrics.reduceOption { (fMetricsAccumulator, fMetricsElement) => FileMetrics( filePath, fMetricsAccumulator.complexity.orElse(fMetricsElement.complexity), fMetricsAccumulator.loc.orElse(fMetricsElement.loc), fMetricsAccumulator.cloc.orElse(fMetricsElement.cloc), fMetricsAccumulator.nrMethods.orElse(fMetricsElement.nrMethods), fMetricsAccumulator.nrClasses.orElse(fMetricsElement.nrClasses), if (fMetricsAccumulator.lineComplexities.nonEmpty) { fMetricsAccumulator.lineComplexities } else { fMetricsElement.lineComplexities }) } }(collection.breakOut) } def calculateMissingFileMetrics( directory: File, metricsResults: Seq[AnalyseExecutor.MetricsToolExecutorResult]): Seq[MetricsToolExecutorResult] = { val fileMetricsByFilePath: Map[Path, FileMetrics] = metricsResults.flatMap { result => result.analysisResults.map(_.map(fileMetrics => (fileMetrics.filename, fileMetrics))).getOrElse(Set.empty) }(collection.breakOut) metricsResults.foldLeft(Seq.empty[MetricsToolExecutorResult]) { case (metricsAccumulator, res @ AnalyseExecutor.MetricsToolExecutorResult(_, _, Success(_))) => metricsAccumulator :+ countMissingLoc(directory, fileMetricsByFilePath, res) case (metricsAccumulator, res @ AnalyseExecutor.MetricsToolExecutorResult(lang, files, Failure(_))) if !metricsResults.exists(r => r.language == lang && r.files == files && r.analysisResults.isSuccess) => metricsAccumulator :+ res :+ countMissingLoc(directory, fileMetricsByFilePath, res) case (metricsAccumulator, res) => metricsAccumulator :+ res } } private def countMissingLoc(directory: File, fileMetricsByFilePath: Map[Path, FileMetrics], metricsRes: AnalyseExecutor.MetricsToolExecutorResult): MetricsToolExecutorResult = { val fileMetrics = metricsRes.files.map { file => fileMetricsByFilePath.get(file) match { case None => FileMetrics( filename = file, nrClasses = None, nrMethods = None, loc = countLoc(directory, file), cloc = None, complexity = None, lineComplexities = Set.empty) case Some(metrics) if metrics.loc.isEmpty => metrics.copy(loc = countLoc(directory, file)) case Some(metrics) => metrics } } metricsRes.copy(analysisResults = Success(fileMetrics)) } private def countLoc(directory: File, file: Path): Option[Int] = { val fileAbsolutePath = (directory / file.toString).path.toAbsolutePath.toString core.utils.FileHelper.countLoc(fileAbsolutePath) } }
Example 78
Source File: CodacyPluginsAnalyser.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.analysis import java.nio.file.Path import better.files.File import com.codacy.analysis.core.model._ import com.codacy.analysis.core.tools.{DuplicationTool, MetricsTool, Tool} import com.codacy.plugins.api.Source import org.log4s.{Logger, getLogger} import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} class CodacyPluginsAnalyser extends Analyser[Try] { private val logger: Logger = getLogger override def analyse(tool: Tool, directory: File, files: Set[Path], config: Configuration, timeout: Option[Duration] = Option.empty[Duration]): Try[Set[ToolResult]] = { val result = tool.run(directory, files, config, timeout) result match { case Success(res) => logger.info(s"Completed analysis for ${tool.name} with ${res.size} results") case Failure(e) => logger.error(e)(Analyser.Error.ToolExecutionFailure("analysis", tool.name).message) } result } override def metrics(metricsTool: MetricsTool, directory: File, files: Option[Set[Path]], timeout: Option[Duration] = Option.empty[Duration]): Try[Set[FileMetrics]] = { val srcFiles = files.map(_.map(filePath => Source.File(filePath.toString))) val result = metricsTool.run(directory, srcFiles, timeout) result match { case Success(res) => logger.info(s"Completed metrics for ${metricsTool.name} with ${res.size} results") case Failure(e) => logger.error(e)(Analyser.Error.ToolExecutionFailure("metrics", metricsTool.name).message) } result.map(_.to[Set]) } override def duplication(duplicationTool: DuplicationTool, directory: File, files: Set[Path], timeout: Option[Duration] = Option.empty[Duration]): Try[Set[DuplicationClone]] = { val result = duplicationTool.run(directory, files, timeout) result match { case Success(res) => logger.info(s"Completed duplication for ${duplicationTool.name} with ${res.size} results") case Failure(e) => logger.error(e)(Analyser.Error.ToolExecutionFailure("duplication", duplicationTool.name).message) } result.map(_.to[Set]) } } object CodacyPluginsAnalyser extends AnalyserCompanion[Try] { val name: String = "codacy-plugins" override def apply(): Analyser[Try] = new CodacyPluginsAnalyser() object errors { def missingTool(tool: String): Analyser.Error = Analyser.Error.NonExistingToolInput(tool, Tool.allToolShortNames) } }
Example 79
Source File: FallbackFileCollectorSpec.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.files import better.files.File import cats.instances.try_.catsStdInstancesForTry import org.specs2.control.NoLanguageFeatures import org.specs2.mutable.Specification import scala.util.{Failure, Success, Try} class FallbackFileCollectorSpec extends Specification with NoLanguageFeatures { private val failingCompanion: FileCollectorCompanion[Try] = new FileCollectorCompanion[Try] { override def name: String = "" override def apply(): FileCollector[Try] = new FileCollector[Try] { override def list(directory: File): Try[FilesTarget] = { Failure(new Exception("because fail")) } } } private val successfulCompanion: FileCollectorCompanion[Try] = new FileCollectorCompanion[Try] { override def name: String = "" override def apply(): FileCollector[Try] = new FileCollector[Try] { override def list(directory: File): Try[FilesTarget] = { Success(FilesTarget(directory, Set.empty, Set.empty)) } } } "FallbackFileCollectorSpec" should { "not fallback" in { new FallbackFileCollector(List(successfulCompanion, failingCompanion)).list(File("")) must beSuccessfulTry } "fallback" in { new FallbackFileCollector(List(failingCompanion, successfulCompanion)).list(File("")) must beSuccessfulTry } "fail when all fail" in { new FallbackFileCollector(List(failingCompanion, failingCompanion)).list(File("")) must beFailedTry } } }
Example 80
Source File: TestingSupport.scala From zio with Apache License 2.0 | 5 votes |
package zio.test.sbt import scala.util.control.NonFatal import scala.util.{ Failure, Try } object TestingSupport { def test[T](l: String)(body: => Unit): Try[Unit] = Try { body println(s"${green("+")} $l") }.recoverWith { case NonFatal(e) => println(s"${red("-")} $l: ${e.getMessage}") e.printStackTrace() Failure(e) } def run(tests: Try[Unit]*) = { val failed = tests.count(_.isFailure) val successful = tests.count(_.isSuccess) val failedCount = if (failed > 0) red(s"failed: $failed") else s"failed: $failed" val successCount = if (successful > 0) green(s"successful: $successful") else s"successful: $successful" println(s"Summary: $failedCount, $successCount") if (failed > 0) throw new AssertionError(s"$failed tests failed") } def assertEquals(what: String, actual: => Any, expected: Any) = assert(actual == expected, s"$what:\n expected: `$expected`\n actual : `$actual`") def colored(code: String)(str: String) = s"$code$str${Console.RESET}" lazy val red = colored(Console.RED) _ lazy val green = colored(Console.GREEN) _ lazy val cyan = colored(Console.CYAN) _ lazy val blue = colored(Console.BLUE) _ def reset(str: String) = s"${Console.RESET}$str" }
Example 81
Source File: AsmTracer.scala From zio with Apache License 2.0 | 5 votes |
package zio.stacktracer.impls import java.lang.invoke.SerializedLambda import scala.util.{ Failure, Success, Try } import org.objectweb.asm._ import zio.internal.stacktracer.Tracer import zio.internal.stacktracer.ZTraceElement.SourceLocation import zio.stacktracer.impls.AsmTracer.MethodSearchVisitor final class AsmTracer extends Tracer { def traceLocation(lambda: AnyRef): SourceLocation = { val clazz = lambda.getClass val classLoader = clazz.getClassLoader Try(clazz.getDeclaredMethod("writeReplace")) match { case Failure(_) => val name = clazz.getName val reader = new ClassReader(classLoader.getResourceAsStream(name.replace('.', '/') + ".class")) val cv = new MethodSearchVisitor("apply", null, Opcodes.ASM7) reader.accept(cv, 0) SourceLocation(cv.sourcefile, name, "apply", cv.line) case Success(replaceMethod) => replaceMethod.setAccessible(true) val sl = replaceMethod.invoke(lambda).asInstanceOf[SerializedLambda] val reader = new ClassReader(classLoader.getResourceAsStream(sl.getImplClass.replace('.', '/') + ".class")) val methodName = sl.getImplMethodName val cv = new MethodSearchVisitor(methodName, sl.getImplMethodSignature, Opcodes.ASM7) reader.accept(cv, 0) val classString = sl.getImplClass.replace('/', '.') SourceLocation(cv.sourcefile, classString, methodName, cv.line) } } } object AsmTracer { final class MethodSearchVisitor( methodName: String, methodSignature: String, apiVersion: Int ) extends ClassVisitor(apiVersion) { var sourcefile: String = _ var line: Int = _ override def visitSource(source: String, debug: String): Unit = sourcefile = source override def visitMethod( access: Int, name: String, descriptor: String, signature: String, exceptions: Array[String] ): MethodVisitor = if (name == methodName && (methodSignature == null || methodSignature == descriptor)) { new MethodVisitor(apiVersion) { override def visitLineNumber(line: Int, start: Label): Unit = MethodSearchVisitor.this.line = line } } else { super.visitMethod(access, name, descriptor, signature, exceptions) } } }
Example 82
Source File: HttpClientVerticle.scala From BusFloatingData with Apache License 2.0 | 5 votes |
package de.nierbeck.vertx.data.stream import io.vertx.lang.scala.ScalaVerticle import io.vertx.scala.ext.web.client.WebClient import io.vertx.scala.ext.web.codec.BodyCodec import de.nierbeck.floating.data.domain.{RouteInfos, Routes, Vehicle} import com.englishtown.vertx.cassandra.CassandraSession import com.englishtown.vertx.cassandra.impl.DefaultCassandraSession import io.vertx.core.{AbstractVerticle, Context, Vertx} import scala.util.{Failure, Success} class HttpClientVerticle extends ScalaVerticle{ val cassandraSession:CassandraSession; override def init(vertx: Vertx, context: Context): Unit = { super.init(vertx,context); cassandraSession = new DefaultCassandraSession(new Cluster.Builder(), new JsonCassandraConfigurator(vertx), vertx) } override def start(): Unit = { cassandraSession.onReady((v) => { def foo(v) = { System.out.printf("==> CASSANDRA SESSION INITIALIZED\n\t[%b]\n", cassandraSession.initialized) startFuture.complete } foo(v) }) var client = WebClient.create(vertx) client.get(80, "api.metro.net", "/agencies/lametro/routes/").as(BodyCodec.json(classOf[RouteInfos])).sendFuture().onComplete{ case Success(result) => { var response = result var routeInfos = response.body() println(s"Received route infos") routeInfos.items.foreach{ routeInfo => { println(s"RouteInfo: ${routeInfo}") }} } case Failure(cause) => { println(s"$cause") } } println("It's the end ...") } }
Example 83
Source File: ServiceApp.scala From BusFloatingData with Apache License 2.0 | 5 votes |
package de.nierbeck.floating.data.server import akka.actor.{ActorRef, ActorSystem, Props} import akka.event.Logging import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model.ws.UpgradeToWebSocket import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri} import akka.stream.ActorMaterializer import de.nierbeck.floating.data.server.actors.websocket.{FLINK, RouterActor, SPARK, TiledVehiclesFromKafkaActor} import scala.concurrent.Await import scala.concurrent.duration.Duration import scala.util.{Failure, Success} object ServiceApp extends RestService { import ServiceConfig._ import system.dispatcher implicit val system = ActorSystem("service-api-http") implicit val mat = ActorMaterializer() override val logger = Logging(system, getClass.getName) override val session = CassandraConnector.connect() def main(args: Array[String]): Unit = { val router: ActorRef = system.actorOf(Props[RouterActor], "router") val sparkKafkaConsumer: ActorRef = system.actorOf(TiledVehiclesFromKafkaActor.props(router, "tiledVehicles", SPARK), "Kafka-Consumer-Spark") val flinkKafkaConsumer: ActorRef = system.actorOf(TiledVehiclesFromKafkaActor.props(router, "flinkTiledVehicles", FLINK), "Kafka-Consumer-Flink") val requestHandler: HttpRequest => HttpResponse = { case req@HttpRequest(GET, Uri.Path("/ws/vehicles"), _, _, _) => req.header[UpgradeToWebSocket] match { case Some(upgrade) => upgrade.handleMessages(Flows.graphFlowWithStats(router)) case None => HttpResponse(400, entity = "Not a valid websocket request!") } case _: HttpRequest => HttpResponse(404, entity = "Unknown resource!") } Http() .bindAndHandle(route(), serviceInterface, servicePort) .onComplete { case Success(_) => logger.info(s"Successfully bound to $serviceInterface:$servicePort") case Failure(e) => logger.error(s"Failed !!!! ${e.getMessage}") } Http() .bindAndHandleSync(requestHandler, serviceInterface, 8001) .onComplete { case Success(_) => logger.info(s"Successfully started Server to $serviceInterface:8001") case Failure(e) => logger.error(s"Failed !!!! ${e.getMessage}") } Await.ready(system.whenTerminated, Duration.Inf) CassandraConnector.close(session) } }
Example 84
Source File: package.scala From BusFloatingData with Apache License 2.0 | 5 votes |
package de.nierbeck.floating.data import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture} import de.nierbeck.floating.data.domain.{BoundingBox, LatLon} import scala.concurrent.{ExecutionContext, Future, Promise} import scala.util.{Failure, Success, Try} package object server { val Traversable = scala.collection.immutable.Traversable type Traversable[+A] = scala.collection.immutable.Traversable[A] val Iterable = scala.collection.immutable.Iterable type Iterable[+A] = scala.collection.immutable.Iterable[A] val Seq = scala.collection.immutable.Seq type Seq[+A] = scala.collection.immutable.Seq[A] val IndexedSeq = scala.collection.immutable.IndexedSeq type IndexedSeq[+A] = scala.collection.immutable.IndexedSeq[A] def futureToFutureTry[T](f: Future[T])(implicit ec: ExecutionContext): Future[Try[T]] = f.map(Success(_)).recover { case exception: Exception => Failure(exception) } implicit class RichListenableFuture[T](lf: ListenableFuture[T]) { def toFuture: Future[T] = { val p = Promise[T]() Futures.addCallback(lf, new FutureCallback[T] { def onFailure(t: Throwable): Unit = p failure t def onSuccess(result: T): Unit = p success result }) p.future } } def toBoundingBox(bbox: String): BoundingBox = { val bboxCoords: Array[String] = bbox.split(",") val boundingBox: BoundingBox = new BoundingBox(LatLon(bboxCoords(0).toFloat, bboxCoords(1).toFloat), LatLon(bboxCoords(2).toFloat, bboxCoords(3).toFloat)) boundingBox } }
Example 85
Source File: DatabaseInitializerImpl.scala From Aton with GNU General Public License v3.0 | 5 votes |
package dao.impl import com.google.inject.{Inject, Singleton} import dao.DatabaseInitializer import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider} import slick.driver.JdbcProfile import slick.driver.H2Driver.api._ import slick.profile.SqlAction import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} @Singleton class DatabaseInitializerImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) extends DatabaseInitializer with HasDatabaseConfigProvider[JdbcProfile] { import driver.api._ def createTables = { val source = scala.io.Source.fromFile("conf/db/create.sql") val query = Try { source.mkString } match { case Success(string) => sqlu"#$string" case Failure(e: Throwable) => play.Logger.error("Error reading conf/db/create.sql file",e) sqlu"""""" } source.close() query } override def initialize(): Future[Int] = db.run { createTables } }
Example 86
Source File: RoomDAOImpl.scala From Aton with GNU General Public License v3.0 | 5 votes |
package dao.impl import javax.inject.Inject import com.google.inject.Singleton import dao.RoomDAO import model.Room import model.table.RoomTable import org.h2.jdbc.JdbcSQLException import play.api.db.slick.DatabaseConfigProvider import play.api.libs.concurrent.Execution.Implicits._ import services.state.ActionState import services.state import slick.driver.JdbcProfile import scala.concurrent.Future import scala.util.{Failure, Success} override def listAll: Future[Seq[Room]] = { db.run(rooms.result) } override def getByLaboratory(id: Long): Future[Seq[Room]] = { db.run(rooms.filter(_.laboratoryId === id).result) } override def update(room: Room): Future[ActionState] = { db.run { val foundLaboratory = search(room.id) foundLaboratory.update(room).asTry }.map{ case Success(res) if res == 1 => play.Logger.info(s"updated with result: $res") state.ActionCompleted case Success(_) => play.Logger.info("Room not found") state.NotFound case Failure(e: JdbcSQLException) => play.Logger.error("There was an error looking for that room",e) state.NotFound case _ => state.Failed } } }
Example 87
Source File: DataSourceEndpoint.scala From akka-visualmailbox with Apache License 2.0 | 5 votes |
package de.aktey.akka.visualmailbox.data import akka.actor.{Actor, ActorLogging, ActorRef, Props} import akka.io.Udp.Received import de.aktey.akka.visualmailbox.packing.Packing import de.aktey.akka.visualmailbox.{MetricEnvelope, VisualMailboxMetric} import scala.util.{Failure, Success} class DataSourceEndpoint(router: ActorRef) extends Actor with ActorLogging { def receive = { case Received(datagram, _) => Packing.unpack[MetricEnvelope](datagram.to[Array]) match { case Success(MetricEnvelope(1, payload)) => Packing.unpack[List[VisualMailboxMetric]](payload) match { case Success(list) => list.foreach(router ! _) case Failure(e) => log.error(e, "unmarshal error") } case Success(MetricEnvelope(version, _)) => log.warning("unknown protocol version: " + version) case Failure(e) => log.error(e, "unmarshal error") } } } object DataSourceEndpoint { def props(router: ActorRef) = Props(new DataSourceEndpoint(router)) }
Example 88
Source File: ControllerProvider.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.router import wvlet.airframe._ import wvlet.airframe.surface.Surface import wvlet.log.LogSupport import scala.util.{Failure, Success, Try} trait ControllerProvider { def findController(session: Session, controllerSurface: Surface): Option[Any] } object ControllerProvider { object defaultControllerProvider extends ControllerProvider with LogSupport { override def findController(session: Session, controllerSurface: Surface): Option[Any] = { Try(session.getInstanceOf(controllerSurface)) match { case Success(controller) => Some(controller) case Failure(e) => warn(e) None } } } }
Example 89
Source File: JMXRegistry.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.jmx
import javax.management._
import wvlet.log.LogSupport
import scala.reflect.runtime.{universe => ru}
import scala.util.{Failure, Try}
private[jmx] def getSimpleClassName(cl: Class[_]): String = {
var name = cl.getName
if (name.endsWith("$")) {
// Remove trailing $ of Scala Object name
name = name.substring(0, name.length - 1)
}
// When class is an anonymous trait
if (name.contains("$anon$")) {
import collection.JavaConverters._
val interfaces = cl.getInterfaces
if (interfaces != null && interfaces.length > 0) {
// Use the first interface name instead of the anonymous name
name = interfaces(0).getName
}
}
// Extract the leaf logger name
val dotPos = name.lastIndexOf(".")
if (dotPos == -1) {
name
} else {
name.substring(dotPos + 1)
}
}
}
Example 90
Source File: TimeParser.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.metrics import java.time._ import java.time.format.DateTimeFormatter import wvlet.log.LogSupport import scala.annotation.tailrec import scala.util.{Failure, Success, Try} object TimeParser extends LogSupport { val localDatePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd") val localDateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]") val zonedDateTimePatterns: List[DateTimeFormatter] = List( "yyyy-MM-dd HH:mm:ss[.SSS][ z][XXXXX][XXXX]['['VV']']", "yyyy-MM-dd'T'HH:mm:ss[.SSS][ z][XXXXX][XXXX]['['VV']']" ).map(DateTimeFormatter.ofPattern(_)) case class TimeParseResult(dateTime: ZonedDateTime, unit: TimeWindowUnit) def parseLocalDateTime(s: String, zone: ZoneOffset): Option[TimeParseResult] = { Try(LocalDateTime.parse(s, localDateTimePattern)) .map { d => TimeParseResult(ZonedDateTime.of(d, zone), TimeWindowUnit.Second) } .orElse { Try(LocalDate.parse(s, localDatePattern)) .map { d => TimeParseResult(d.atStartOfDay(zone), TimeWindowUnit.Day) } } .toOption } def parseZonedDateTime(s: String): Option[TimeParseResult] = { @tailrec def loop(lst: List[DateTimeFormatter]): Option[TimeParseResult] = { if (lst.isEmpty) { None } else { val formatter = lst.head Try(ZonedDateTime.parse(s, formatter)) match { case Success(dt) => Some(TimeParseResult(dt, TimeWindowUnit.Second)) case Failure(e) => loop(lst.tail) } } } loop(zonedDateTimePatterns.toList) } def parseAtLocalTimeZone(s: String): Option[ZonedDateTime] = parse(s, systemTimeZone) def parse(s: String, zone: ZoneOffset): Option[ZonedDateTime] = { parseTimeAndUnit(s, zone).map(_.dateTime) } def parseTimeAndUnit(s: String, zone: ZoneOffset): Option[TimeParseResult] = { parseLocalDateTime(s, zone) .orElse(parseZonedDateTime(s)) } }
Example 91
Source File: Count.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.metrics import wvlet.airframe.metrics.Count.CountUnit import wvlet.airframe.surface.{Surface, Zero} import scala.annotation.tailrec import scala.util.{Failure, Success, Try} object Count { Zero.register(Surface.of[CountUnit], ONE) Zero.register(Surface.of[Count], Count(0)) val units = List(ONE, THOUSAND, MILLION, BILLION, TRILLION, QUADRILLION) private val unitTable = units.map(x => x.unitString -> x).toMap[String, CountUnit] sealed class CountUnit private[metrics] (val factor: Long, val unitString: String) { override def toString = unitString } case object ONE extends CountUnit(1L, "") case object THOUSAND extends CountUnit(1000L, "K") case object MILLION extends CountUnit(1000000L, "M") case object BILLION extends CountUnit(1000000000L, "B") case object TRILLION extends CountUnit(1000000000000L, "T") case object QUADRILLION extends CountUnit(1000000000000000L, "Q") object CountUnit { // deserializer for airframe-codec def unapply(unitString: String): Option[CountUnit] = units.find(_.unitString == unitString) } def succinct(x: Long): Count = { Count(x, ONE).mostSuccinctCount } def apply(value: Long): Count = Count(value, ONE) def unapply(countStr: String): Option[Count] = Try(apply(countStr)).toOption private val countPattern = """^\s*((?:-?)?[\d,]+(?:\.\d+)?)\s*([a-zA-Z])\s*$""".r("num", "unit") def apply(countStr: String): Count = { countPattern.findFirstMatchIn(countStr) match { case None => // When no unit string is found val normalized = countStr.replaceAll(",", "") Try(normalized.toLong) match { case Success(v) => Count(v) case Failure(e) => // Try parsing as double Try(normalized.toDouble) match { case Success(d) => Count(d.toLong) case Failure(e) => throw new IllegalArgumentException(s"Invalid count string: ${countStr}") } } case Some(m) => val num = m.group("num").replaceAll(",", "").toDouble val unit = m.group("unit") unitTable.get(unit) match { case None => throw new IllegalArgumentException(s"Invalid count unit ${unit} in ${countStr}") case Some(u) => Count((num * u.factor).round, u) } } } }
Example 92
Source File: OkHttpRetryInterceptor.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.okhttp import okhttp3.{Interceptor, Response} import wvlet.airframe.control.ResultClass import wvlet.airframe.control.Retry.RetryContext import wvlet.airframe.http.HttpClientMaxRetryException import scala.util.control.NonFatal import scala.util.{Failure, Success, Try} class OkHttpRetryInterceptor(retry: RetryContext) extends Interceptor { private def dispatch(retryContext: RetryContext, chain: Interceptor.Chain): Response = { val request = chain.request() val response = Try(chain.proceed(request)) val resultClass = response match { case Success(r) => try { retryContext.resultClassifier(r) } catch { case NonFatal(e) => retryContext.errorClassifier(e) } case Failure(e) => retryContext.errorClassifier(e) } resultClass match { case ResultClass.Succeeded => response.get case ResultClass.Failed(isRetryable, cause, extraWait) => if (!retryContext.canContinue) { // Reached the max retry throw HttpClientMaxRetryException(OkHttpResponseWrapper(response.toOption.orNull), retryContext, cause) } else if (!isRetryable) { // Non-retryable failure throw cause } else { // Update the retry count val nextRetryContext = retryContext.withExtraWait(extraWait).nextRetry(cause) // Wait until the next retry Thread.sleep(nextRetryContext.nextWaitMillis) // Run the same request again dispatch(nextRetryContext, chain) } } } override def intercept(chain: Interceptor.Chain): Response = { val request = chain.request() val retryContext = retry.init(Option(request)) dispatch(retryContext, chain) } }
Example 93
Source File: TimeCodec.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.codec import java.time.Instant import java.util.Date import wvlet.airframe.msgpack.io.ByteArrayBuffer import wvlet.airframe.msgpack.spi._ import wvlet.log.LogSupport import scala.util.{Failure, Success, Try} object JavaInstantTimeCodec extends MessageCodec[Instant] { override def pack(p: Packer, v: Instant): Unit = { // TODO airframe-msgpack in Codec interface // Use msgpack Timestamp type val buf = ByteArrayBuffer.newBuffer(15) val cursor = WriteCursor(buf, 0) OffsetPacker.packTimestamp(cursor, v) val extData = buf.readBytes(0, cursor.lastWrittenBytes) p.writePayload(extData, 0, cursor.lastWrittenBytes) } override def unpack(u: Unpacker, v: MessageContext): Unit = { Try { u.getNextFormat.getValueType match { case ValueType.STRING => // Use ISO instant formatter val isoInstantFormat = u.unpackString wvlet.airframe.codec.Compat .parseInstant(isoInstantFormat) .getOrElse(Instant.ofEpochMilli(isoInstantFormat.toLong)) case ValueType.INTEGER => val epochMillis = u.unpackLong Instant.ofEpochMilli(epochMillis) case ValueType.EXTENSION => u.unpackTimestamp case other => v.setIncompatibleFormatException(this, s"Cannot create Instant from ${other} type") } } match { case Success(x) => v.setObject(x) case Failure(e) => v.setError(e) } } } object JavaUtilDateCodec extends MessageCodec[Date] with LogSupport { override def pack(p: Packer, v: Date): Unit = { // Use Instant for encoding JavaInstantTimeCodec.pack(p, v.toInstant) } override def unpack(u: Unpacker, v: MessageContext): Unit = { JavaInstantTimeCodec.unpack(u, v) if (!v.isNull) { v.setObject(Date.from(v.getLastValue.asInstanceOf[Instant])) } } }
Example 94
Source File: JavaTimeCodec.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.codec import java.time.{Instant, ZonedDateTime} import java.util.Date import wvlet.airframe.msgpack.io.ByteArrayBuffer import wvlet.airframe.msgpack.spi._ import wvlet.airframe.surface.Surface import wvlet.log.LogSupport import scala.util.{Failure, Success, Try} object JavaTimeCodec { val javaTimeCodecs = Map( Surface.of[ZonedDateTime] -> ZonedDateTimeCodec, Surface.of[Date] -> JavaUtilDateCodec ) object ZonedDateTimeCodec extends MessageCodec[ZonedDateTime] { override def pack(p: Packer, v: ZonedDateTime): Unit = { // Use java standard ZonedDateTime string repr such as "2007-12-03T10:15:30+01:00[Europe/Paris]" p.packString(v.toString) } override def unpack(u: Unpacker, v: MessageContext): Unit = { val zonedDateTimeStr = u.unpackString Try(ZonedDateTime.parse(zonedDateTimeStr)) match { case Success(zd) => v.setObject(zd) case Failure(e) => v.setIncompatibleFormatException( this, s"${zonedDateTimeStr} cannot be read as ZonedDateTime: ${e.getMessage}" ) } } } }
Example 95
Source File: FinagleBackend.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import java.util.concurrent.atomic.AtomicReference import com.twitter.finagle.Service import com.twitter.finagle.context.Contexts import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.{Future, Promise, Return, Throw} import wvlet.airframe.http.{HttpBackend, HttpRequestAdapter, HttpStatus} import wvlet.log.LogSupport import scala.concurrent.ExecutionContext import scala.util.{Failure, Success} import scala.{concurrent => sc} object FinagleBackend extends HttpBackend[Request, Response, Future] { override protected implicit val httpRequestAdapter: HttpRequestAdapter[Request] = FinagleHttpRequestAdapter override def wrapException(e: Throwable): Future[Response] = { Future.exception(e) } override def newResponse(status: HttpStatus, content: String): Response = { val r = Response(Status.fromCode(status.code)) r.contentString = content r } def wrapFilter(filter: com.twitter.finagle.Filter[Request, Response, Request, Response]): FinagleFilter = { new FinagleFilter with LogSupport { override def apply(request: Request, context: Context): Future[Response] = { filter(request, Service.mk { req: Request => context(req) }) } } } override def toFuture[A](a: A): Future[A] = Future.value(a) override def toScalaFuture[A](a: Future[A]): sc.Future[A] = { val promise: sc.Promise[A] = sc.Promise() a.respond { case Return(value) => promise.success(value) case Throw(exception) => promise.failure(exception) } promise.future } override def toFuture[A](a: sc.Future[A], e: ExecutionContext): Future[A] = { val promise: Promise[A] = Promise() a.onComplete { case Success(value) => promise.setValue(value) case Failure(exception) => promise.setException(exception) }(e) promise } override def isFutureType(cl: Class[_]): Boolean = { classOf[Future[_]].isAssignableFrom(cl) } override def isRawResponseType(cl: Class[_]): Boolean = { classOf[Response].isAssignableFrom(cl) } override def mapF[A, B](f: Future[A], body: A => B): Future[B] = { f.map(body) } private val contextParamHolderKey = new Contexts.local.Key[AtomicReference[collection.mutable.Map[String, Any]]] override def withThreadLocalStore(body: => Future[Response]): Future[Response] = { val newParamHolder = collection.mutable.Map.empty[String, Any] Contexts.local .let(contextParamHolderKey, new AtomicReference[collection.mutable.Map[String, Any]](newParamHolder)) { body } } override def setThreadLocal[A](key: String, value: A): Unit = { Contexts.local.get(contextParamHolderKey).foreach { ref => ref.get().put(key, value) } } override def getThreadLocal[A](key: String): Option[A] = { Contexts.local.get(contextParamHolderKey).flatMap { ref => ref.get.get(key).asInstanceOf[Option[A]] } } }
Example 96
Source File: SSMUtil.scala From CloudGenesis with Apache License 2.0 | 5 votes |
package com.lifeway.cloudops.cloudformation import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder import com.amazonaws.services.simplesystemsmanagement.model.GetParameterRequest import org.scalactic.{Bad, Good, Or} import scala.util.{Failure, Success, Try} trait SSMUtil { val ssm = AWSSimpleSystemsManagementClientBuilder.defaultClient() def getSSMParam(path: String): String Or SSMError = { val req: GetParameterRequest = new GetParameterRequest().withName(path).withWithDecryption(true) Try { ssm.getParameter(req).getParameter.getValue } match { case Success(value) => Good(value) case Failure(t) => Bad(SSMDefaultError(t.getMessage)) } } } sealed trait SSMError case class SSMDefaultError(msg: String) extends SSMError object DefaultSSMUtil extends SSMUtil
Example 97
Source File: TwitterSpec.scala From interop-twitter with Apache License 2.0 | 5 votes |
package zio.interop import java.util.concurrent.atomic.AtomicInteger import com.twitter.util.{ Await, Future, Promise } import zio.{ Task, ZIO } import zio.interop.twitter._ import zio.test._ import zio.test.Assertion._ import scala.util.{ Failure, Success, Try } object TwitterSpec extends DefaultRunnableSpec { val runtime = runner.runtime override def spec = suite("TwitterSpec")( suite("Task.fromTwitterFuture")( testM("return failing `Task` if future failed.") { val error = new Exception val future = Task(Future.exception[Int](error)) val task = Task.fromTwitterFuture(future).unit assertM(task.either)(isLeft(equalTo(error))) }, testM("return successful `Task` if future succeeded.") { val value = 10 val future = Task(Future.value(value)) val task = Task.fromTwitterFuture(future).option assertM(task)(isSome(equalTo(value))) }, testM("ensure future is interrupted together with task.") { val value = new AtomicInteger(0) val promise = new Promise[Unit] with Promise.InterruptHandler { override protected def onInterrupt(t: Throwable): Unit = setException(t) } val future = Task(promise.flatMap(_ => Future(value.incrementAndGet()))) val task = (for { fiber <- Task.fromTwitterFuture(future).fork _ <- fiber.interrupt _ <- Task.effect(promise.setDone()) a <- fiber.await } yield a).fold(_ => false, exit => exit.toEither.isLeft) task.map(b => assert(b)(isTrue) && assert(value.get())(equalTo(0))) } ), suite("Runtime.unsafeRunToTwitterFuture")( test("return successful `Future` if Task evaluation succeeded.") { assert(Await.result(runtime.unsafeRunToTwitterFuture(Task.succeed(2))))(equalTo(2)) }, test("return failed `Future` if Task evaluation failed.") { val e = new Throwable val task = Task.fail(e).unit val result = Try(Await.result(runtime.unsafeRunToTwitterFuture(task))) match { case Failure(exception) => Some(exception) case Success(_) => None } assert(result)(isSome(equalTo(e))) }, testM("ensure Task evaluation is interrupted together with Future.") { val value = new AtomicInteger(0) val ex = new Exception val task: ZIO[Any, Throwable, Future[Int]] = for { promise <- zio.Promise.make[Throwable, Int] t = promise.await.flatMap(_ => Task.effectTotal(value.incrementAndGet())) future = runtime.unsafeRunToTwitterFuture(t) _ = future.raise(ex) _ <- promise.succeed(1) } yield future assertM(task.map(Await.result(_)).run)(isInterrupted).map(_ && assert(value.get)(equalTo(0))) } ) ) }
Example 98
Source File: SlowLogMiddleware.scala From naptime with Apache License 2.0 | 5 votes |
package org.coursera.naptime.ari.graphql.controllers.middleware import com.typesafe.scalalogging.Logger import org.coursera.naptime.ari.graphql.SangriaGraphQlContext import sangria.execution.BeforeFieldResult import sangria.execution.Extension import sangria.execution.Middleware import sangria.execution.MiddlewareAfterField import sangria.execution.MiddlewareExtension import sangria.execution.MiddlewareQueryContext import sangria.schema.Context import sangria.execution.MiddlewareErrorField import sangria.slowlog.SlowLog import sangria.slowlog.QueryMetrics import scala.concurrent.duration._ import scala.util.Failure import scala.util.Success import scala.util.Try class SlowLogMiddleware(logger: Logger, isDebugMode: Boolean) extends Middleware[SangriaGraphQlContext] with MiddlewareExtension[SangriaGraphQlContext] with MiddlewareAfterField[SangriaGraphQlContext] with MiddlewareErrorField[SangriaGraphQlContext] { type QueryVal = QueryMetrics type FieldVal = Long private[this] val underlying = { if (isDebugMode) { SlowLog.extension } else { SlowLog(logger.underlying, threshold = 6 seconds) } } override def beforeQuery( context: MiddlewareQueryContext[SangriaGraphQlContext, _, _]): QueryMetrics = underlying.beforeQuery(context) override def afterQuery( queryVal: QueryMetrics, context: MiddlewareQueryContext[SangriaGraphQlContext, _, _]): Unit = underlying.afterQuery(queryVal, context) override def afterQueryExtensions( queryVal: QueryMetrics, context: MiddlewareQueryContext[SangriaGraphQlContext, _, _]): Vector[Extension[_]] = underlying.afterQueryExtensions(queryVal, context) // The next 2 functions are parametrized on `SangriaGraphQlContext` which makes them not usable // when directly passed into the delegate. Instead, we have to do a (safe) typecast. It is // wrapped as a `Try` to avoid future runtime errors. override def afterField( queryVal: QueryMetrics, fieldVal: Long, value: Any, mctx: MiddlewareQueryContext[SangriaGraphQlContext, _, _], ctx: Context[SangriaGraphQlContext, _]): Option[Any] = { val safeContext = Try(ctx.asInstanceOf[Context[Any, _]]) safeContext match { case Success(c) => underlying.afterField(queryVal, fieldVal, value, mctx, c) case Failure(_) => None } } override def fieldError( queryVal: QueryMetrics, fieldVal: Long, error: Throwable, mctx: MiddlewareQueryContext[SangriaGraphQlContext, _, _], ctx: Context[SangriaGraphQlContext, _]): Unit = { val safeContext = Try(ctx.asInstanceOf[Context[Any, _]]) safeContext match { case Success(c) => underlying.fieldError(queryVal, fieldVal, error, mctx, c) case Failure(_) => () } } // We cannot use the same type casting method as the above 2 classes because the return type // is parametrized, so we just copy the underlying impl. It is very straightforward [just // recording the timestamp] so we don't think it will change. override def beforeField( queryVal: QueryMetrics, mctx: MiddlewareQueryContext[SangriaGraphQlContext, _, _], ctx: Context[SangriaGraphQlContext, _]): BeforeFieldResult[SangriaGraphQlContext, Long] = continue(System.nanoTime()) }
Example 99
Source File: RemoteDirectory.scala From dependency with MIT License | 5 votes |
package io.flow.dependency.api.lib import io.flow.dependency.v0.models.{Credentials, CredentialsUndefinedType, UsernamePassword} import org.htmlcleaner.HtmlCleaner import org.apache.commons.codec.binary.Base64 import org.apache.commons.lang3.StringUtils import org.apache.commons.text.StringEscapeUtils import java.net.URL import scala.util.{Failure, Success, Try} object RemoteDirectory { case class Result( directories: Seq[String] = Nil, files: Seq[String] = Nil ) def fetch( url: String, credentials: Option[Credentials] = None ) ( filter: String => Boolean = { !_.startsWith(".") } ): Result = { val base = Result() val cleaner = new HtmlCleaner() val uc = (new URL(url)).openConnection() credentials.map { cred => cred match { case UsernamePassword(username, password) =>{ val userpass = username + ":" + password.getOrElse("") val basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())) uc.setRequestProperty ("Authorization", basicAuth) } case CredentialsUndefinedType(_) => { // No-op } } } Try(cleaner.clean(uc.getInputStream())) match { case Failure(_) => { base } case Success(rootNode) => { rootNode.getElementsByName("a", true).foldLeft(base) { case (result, elem) => Option(elem.getAttributeByName("href")) match { case None => { result } case Some(_) => { val text = StringEscapeUtils.unescapeHtml4(elem.getText.toString) filter(StringUtils.stripEnd(text, "/")) match { case false => { result } case true => { text.endsWith("/") match { case true => result.copy(directories = result.directories ++ Seq(text)) case false => result.copy(files = result.files ++ Seq(text)) } } } } } } } } } }
Example 100
Source File: Validation.scala From dependency with MIT License | 5 votes |
package io.flow.dependency.api.lib import scala.util.{Failure, Success, Try} import java.net.URI object Validation { def validateUri(uri: String): Either[Seq[String], URI] = { uri.trim match { case "" => Left(Seq(s"URI cannot be an empty string")) case trimmed => { if (trimmed.toLowerCase.startsWith("http")) { Try(URI.create(trimmed)) match { case Failure(error) => Left(Seq(s"Could not parse uri[$trimmed]: $error")) case Success(u) => Right(u) } } else { Left(Seq("URI must start with http")) } } } } }
Example 101
package flaky import java.io._ import java.net.{HttpURLConnection, URL} import java.util.Scanner import sbt.{File, Logger} import scala.language.postfixOps import scala.util.{Failure, Success, Try} object Io { def writeToFile(file: File, content: String): Unit = { new PrintWriter(file) { write(content) close() } } def writeToFile(file: File, content: Array[Byte]): Unit = { new FileOutputStream(file) { write(content) close() } } def writeToFile(file: File, is: InputStream): Unit = { val array: Array[Byte] = Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray writeToFile(file, array) } def sendToSlack(webHook: String, jsonMsg: String, log: Logger, backupFile: File): Unit = { log.info("Sending report to slack") log.debug("Dumping slack msg to file") new PrintWriter(backupFile) { write(jsonMsg) close() } val send: Try[Unit] = Try { val url = new URL(webHook) val urlConnection = url.openConnection().asInstanceOf[HttpURLConnection] // Indicate that we want to write to the HTTP request body urlConnection.setDoOutput(true) urlConnection.setRequestMethod("POST") // Writing the post data to the HTTP request body log.debug(jsonMsg) val httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream)) httpRequestBodyWriter.write(jsonMsg) httpRequestBodyWriter.close() val scanner = new Scanner(urlConnection.getInputStream) log.debug("Response from SLACK:") while (scanner.hasNextLine) { log.debug(s"Response from SLACK: ${scanner.nextLine()}") } scanner.close() } send match { case Success(_) => log.info("Notification successfully send to Slack") case Failure(e) => log.error(s"Can't send message to slack: ${e.getMessage}") } } }
Example 102
package flaky.history import java.io.File import org.eclipse.jgit.api.{Git => JGit} import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.storage.file.FileRepositoryBuilder import scala.annotation.tailrec import scala.collection.JavaConverters._ import scala.util.{Failure, Success, Try} object Git { def apply(workTree: File): Git = { @tailrec def findGitRoot(dir: File, upLevels: Int): File = { if (upLevels > 0) { val git = new GitUsingJgit((new FileRepositoryBuilder).setWorkTree(dir).build()) val triedString = git.currentId() triedString match { case Success(_) => dir case Failure(_) if dir.getParentFile != null => findGitRoot(dir.getParentFile, upLevels - 1) case Failure(_) => dir } } else { dir } } val gitRoot = findGitRoot(workTree, 3) new GitUsingJgit((new FileRepositoryBuilder).setWorkTree(gitRoot).build()) } } trait Git { def currentId(): Try[String] def history(): Try[List[GitCommit]] def commitsList(previous: String, current: String): Try[List[GitCommit]] = { history().map(_.dropWhile(_.id != current).takeWhile(_.id != previous)) } def remoteUrl(): Try[String] } class GitUsingJgit(repository: Repository) extends Git { private val jgit = new JGit(repository) def currentId(): Try[String] = Try { jgit.log .setMaxCount(1) .call() .asScala .map(_.getId.abbreviate(7).name) .head } def history(): Try[List[GitCommit]] = Try { jgit.log .add(repository.resolve("master")) .call() .asScala .toList .map(fullDesc) } private def fullDesc(commit: RevCommit) = GitCommit( commit.getId.abbreviate(7).name, commit.getAuthorIdent.getEmailAddress, commit.getShortMessage, commit.getCommitTime ) override def remoteUrl(): Try[String] = { Try { repository.getConfig.getString("remote", "origin", "url") } match { case Success(null) => Failure(new Exception("No remote repo found")) case Success(s) => Success(s) case Failure(ex) => Failure(ex) } } } case class GitCommit(id: String, author: String, shortMsg: String, commitTime: Int)
Example 103
Source File: AuthzUtils.scala From spark-authorizer with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.hive import scala.util.{Failure, Success, Try} private[hive] object AuthzUtils { def getFieldVal(o: Any, name: String): Any = { Try { val field = o.getClass.getDeclaredField(name) field.setAccessible(true) field.get(o) } match { case Success(value) => value case Failure(exception) => throw exception } } def setFieldVal(o: Any, name: String, value: Any): Unit = { Try { val field = o.getClass.getDeclaredField(name) field.setAccessible(true) field.set(o, value.asInstanceOf[AnyRef]) } match { case Failure(exception) => throw exception case _ => } } }
Example 104
Source File: AllowEmptySqlArrayValueConstructor.scala From schedoscope with Apache License 2.0 | 5 votes |
package org.schedoscope.lineage.parser import org.apache.calcite.rel.`type`.RelDataType import org.apache.calcite.sql.{SqlCallBinding, SqlOperatorBinding} import org.apache.calcite.sql.`type`.{SqlTypeName, SqlTypeUtil} import org.apache.calcite.sql.fun.SqlArrayValueConstructor import org.apache.calcite.util.Static.RESOURCE import scala.util.{Failure, Success, Try} object AllowEmptySqlArrayValueConstructor extends SqlArrayValueConstructor { override def checkOperandTypes(callBinding: SqlCallBinding, throwOnFailure: Boolean): Boolean = { val argTypes = SqlTypeUtil.deriveAndCollectTypes(callBinding.getValidator, callBinding.getScope, callBinding.getCall.getOperandList) if (!argTypes.isEmpty && getComponentType(callBinding.getTypeFactory, argTypes) == null) { if (throwOnFailure) throw callBinding.newValidationError(RESOURCE.needSameTypeParameter) else false } else true } override def inferReturnType(opBinding: SqlOperatorBinding): RelDataType = Try(super.inferReturnType(opBinding)) match { case Success(t) => t case Failure(_) => SqlTypeUtil.createArrayType(opBinding.getTypeFactory, opBinding.getTypeFactory.createSqlType(SqlTypeName.ANY), false) } }
Example 105
Source File: TestUtils.scala From schedoscope with Apache License 2.0 | 5 votes |
package org.schedoscope.test import org.schedoscope.dsl.FieldLike import org.schedoscope.lineage.NoHiveTransformationException import scala.util.{Failure, Success} object TestUtils { def loadView(view: LoadableView, sortedBy: FieldLike[_], disableDependencyCheck: Boolean, disableTransformationValidation: Boolean, disableLineageValidation: Boolean) = { //dependencyCheck if (!disableDependencyCheck) { if (!view.checkDependencies()) { throw new IllegalArgumentException("The input views to the test given by basedOn() do not cover all types of dependencies of the view under test.") } } // lineage validation if (!disableLineageValidation && view.explicitLineage.isEmpty && view.dependencies.nonEmpty) { view.tryLineage match { case Success(_) => case Failure(ex) => ex match { case _: NoHiveTransformationException => case _ => throw ex } } } view.loadLocalResources() val resources = view.resources val inputFixtures = view.inputFixtures // edge case to solve issue with recursive dependencies var recursiveView = false inputFixtures.foreach { v => if (v.n == view.n && !recursiveView) { println(s"[Schedoscope INFO]: The View you are testing - ${view.n} - depends on itself " + s"(specified with dependsOn {} method). In these edge cases Schedoscope also changes Storage " + s"format of output files into TextFile() of the view being tested (besides for its input views). " + s"You can safely ignore this message, as this should not affect the logic of your tests.") view.storedAs(resources.textStorage) recursiveView = true } } inputFixtures.foreach(_.writeData()) view.createViewTable() if (view.isPartitioned()) { resources.schemaManager.createPartition(view) } val declaredTransformation = view.registeredTransformation() //transformation validation if (!(disableTransformationValidation || view.dependencyCheckDisabled)) declaredTransformation.validateTransformation() val transformationRiggedForTest = resources .driverFor(declaredTransformation) .rigTransformationForTest(declaredTransformation, resources) view.registeredTransformation = () => transformationRiggedForTest // // Patch export configurations to point to the test metastore with no kerberization. // view.configureExport("schedoscope.export.isKerberized", false) view.configureExport("schedoscope.export.kerberosPrincipal", "") view.configureExport("schedoscope.export.metastoreUri", resources.metastoreUri) val finalTransformationToRun = view.transformation() resources .driverFor(finalTransformationToRun) .runAndWait(finalTransformationToRun) if (sortedBy != null) { view.populate(Some(sortedBy)) } else { view.populate(view.sortedBy) } } }
Example 106
Source File: FileUtils.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.util import org.apache.log4j.Logger import scala.io.Source._ import scala.util.{Failure, Success, Try} def write(content: String, pathName: String, className: String): Boolean = { import java.io.PrintWriter import DisplayUtils._ var printWriter: Option[PrintWriter] = None var status = false Try { printWriter = Some(new PrintWriter(pathName)) printWriter.foreach(_.write(content)) printWriter.foreach(_.flush) printWriter.foreach(_.close) status = true } match { // Catch and display exception description and return false case Failure(e) => error(s"$className.write failed for $pathName", logger, e) if (printWriter.isDefined) printWriter.foreach(_.close) status case Success(s) => status } } } // --------------------------------- EOF -------------------------------------
Example 107
Source File: WorkflowTest.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.workflow import org.scalaml.Logging import org.scalaml.core.Design.{ConfigDouble, ConfigInt} import org.scalaml.core.ETransform import org.scalaml.Predef._ import org.scalaml.stats.MinMax import org.scalatest.{FlatSpec, Matchers} import scala.util.{Failure, Random, Success, Try} final class WorkflowTest extends FlatSpec with Matchers with Logging { protected[this] val name = "Workflow for data pipeline" it should s"$name Illustration of a monadic workflow" in { val samples: Int = 100 val normRatio = 10 val splits = 4 val g = (x: Double) => Math.log(x + 1.0) + Random.nextDouble val workflow = new Workflow[Double => Double, DblVec, DblVec, Int] with Sampling[Double => Double, DblVec] with Normalization[DblVec, DblVec] with Aggregation[DblVec, Int] { val sampler = new ETransform[Double => Double, DblVec](ConfigInt(samples)) { override def |> : PartialFunction[Double => Double, Try[DblVec]] = { case f: (Double => Double) => Try { val sampled: DblVec = Vector.tabulate(samples)(n => f(n.toDouble / samples)) show(s"$name sampling : ${sampled.mkString(",")}") sampled } } } val normalizer = new ETransform[DblVec, DblVec](ConfigDouble(normRatio)) { override def |> : PartialFunction[DblVec, Try[DblVec]] = { case x: DblVec if x.nonEmpty => Try { val minMax = MinMax[Double](x).map(_.normalize(0.0, 1.0)).getOrElse(Vector.empty[Double]) show(s"$name normalization : ${minMax.mkString(",")}") minMax } } } val aggregator = new ETransform[DblVec, Int](ConfigInt(splits)) { override def |> : PartialFunction[DblVec, Try[Int]] = { case x: DblVec if x.nonEmpty => Try { show(s"$name aggregation") Range(0, x.size).find(x(_) == 1.0).getOrElse(-1) } } } } (workflow |> g) match { case Success(res) => show(s"$name result = ${res.toString}") case Failure(e) => error(s"$name", e) } } } // --------------------------------------- EOF ----------------------------------------------
Example 108
Source File: DKalmanTest.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.filtering.kalman
import org.scalaml.{Logging, Predef, Resource}
import org.scalaml.Predef.DblVec
import org.scalaml.stats.TSeries.zipWithShift
import org.scalaml.trading.YahooFinancials
import org.scalaml.trading.YahooFinancials.adjClose
import org.scalaml.util.Assertable
import org.scalaml.util.FormatUtils.{LONG, format}
import org.scalaml.workflow.data.{DataSink, DataSource}
import org.scalatest.{FlatSpec, Matchers}
import scala.util.{Failure, Random, Success}
final class DKalmanTest extends FlatSpec with Matchers with Logging with Assertable with Resource {
protected[this] val name: String = "Kalman filter"
private val OUTPUT_FILE = "output/filtering/dkalman"
private val RESOURCE_DIR = "filtering/"
private val NUM_VALUES = 128
// Noise has to be declared implicitly
implicit val qrNoise = new QRNoise((0.7, 0.3), (m: Double) => m * Random.nextGaussian)
// Contract extractor
private val extractor = YahooFinancials.adjClose :: List[Array[String] => Double]()
it should s"$name evaluation" in {
import Predef._
show(s"$name evaluation")
// H and P0 are the only components that are independent from
// input data and smoothing factor. The control matrix B is not defined
// as there is no external control on the time series.
val H: DblMatrix = ((0.9, 0.0), (0.0, 0.1))
val P0: DblMatrix = ((0.4, 0.3), (0.5, 0.4))
private def display(z: DblVec, x: DblVec, alpha: Double): Unit = {
import org.scalaml.plots.{LinePlot, LightPlotTheme, Legend}
val labels = Legend(
name, s"Kalman filter alpha = $alpha", s"Kalman with alpha $alpha", "y"
)
val data = (z, "price") :: (x, "Filtered") :: List[(DblVec, String)]()
LinePlot.display(data, labels, new LightPlotTheme)
}
}
// -------------------------------- EOF ----------------------------------------------------
Example 109
Source File: ITransformTest.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.core import org.scalaml.Logging import org.scalatest.{FlatSpec, Matchers} import scala.util.{Failure, Success, Try} class ExpTransform(x: Vector[Float]) extends ITransform[Float, Vector[Double]] { override def |> : PartialFunction[Float, Try[Vector[Double]]] = { case y: Float if Math.abs(y) < 100 => Try(x.map(t => Math.exp(t * y))) } } // instantiate the transformation val input = Vector[Float](1.6F, 8.0F, -0.4F) val expTransform = new ExpTransform(input) // Get the new ITransform and compare the values generated by // the Vector.map and -iTransform.map val expected = input.map(_ * 2.0) val doubleValue = (x: Vector[Double]) => x.map(_ * 2.0) val found: Try[Vector[Double]] = expTransform.map(doubleValue) |> 2.0F found.toOption.isDefined should be (true) (found.get)(0) should be(49.1 +- 0.1) // Apply the transformation exp(factor * _) to the input vector val factor = 2.5F expTransform |> factor match { case Success(res) => show(s"Vector( ${input.mkString(", ")} ) by exp($factor * _)\n = Vector( ${res.mkString(", ")} )") case Failure(e) => error(e.toString) } } it should s"$name composition" in { object _ITransformApp extends App { val it1 = new ITransform[Double, Double] { def |> : PartialFunction[Double, Try[Double]] = { case x: Double if x > 0.0 => Try[Double](x * 2.0) } } val it2 = new ITransform[Double, Int] { def |> : PartialFunction[Double, Try[Int]] = { case y: Double if y > 1 => Try[Int]((y + 8.0).toInt) } } val value = for { n1 <- it1 n2 <- it2 } yield { n2 } show(s"$name value ${value.|>(3.0)}") val combined: Try[Int] = it1.compose(it2).|>(3.0) show(s"$name combined $combined") } } }
Example 110
Source File: FutureEffect.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch06 import scala.concurrent.{ExecutionContext, Future} import ExecutionContext.Implicits.global import scala.util.{Failure, Success, Try} trait FutureEffect { val runningForever = Future { while (true) Thread.sleep(1000) } val stringFuture = Future.successful("Well") val failure = Future.failed(new IllegalArgumentException) val fromTry = Future.fromTry(Try(10 / 0)) val runningLong = Future.unit.map { _ => while (math.random() > 0.001) Thread.sleep(100) } runningLong.foreach(_ => println("First callback")) runningLong.foreach(_ => println("Second callback")) runningLong.onComplete { case Success(value) => println(s"Success with $value") case Failure(ex) => println(s"Failure with $ex") } stringFuture.transform(_.length, ex => new Exception(ex)) stringFuture.transform { case Success(value) => Success(value.length) case Failure(ex) => Failure(new Exception(ex)) } stringFuture.filter(_.length > 10) stringFuture.collect { case s if s.length > 10 => s.toUpperCase } if (runningLong.isCompleted) runningLong.value runningForever.value match { case Some(Success(value)) => println(s"Finished successfully with $value") case Some(Failure(exception)) => println(s"Failed with $exception") case None => println("Still running") } } trait FishingFutureExample { import Effects._ trait plain { val buyBait: String => Bait val makeBait: String => Bait val castLine: Bait => Line val hookFish: Line => Fish def goFishing(bestBaitForFish: Future[String]): Future[Fish] = bestBaitForFish.map(buyBait).map(castLine).map(hookFish) } trait flat { val buyBait: String => Future[Bait] val makeBait: String => Future[Bait] val castLine: Bait => Future[Line] val hookFish: Line => Future[Fish] def goFishing(bestBaitForFish: Future[String]): Future[Fish] = for { baitName <- bestBaitForFish bait <- buyBait(baitName).fallbackTo(makeBait(baitName)) line <- castLine(bait) fish <- hookFish(line) } yield fish } }
Example 111
Source File: Applicative.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import scala.language.{higherKinds, reflectiveCalls} import scala.util.{Failure, Success, Try} trait Applicative[F[_]] extends Functor[F] { def apply[A,B](a: F[A])(f: F[A => B]): F[B] def unit[A](a: => A): F[A] override def map[A,B](fa: F[A])(f: A => B): F[B] = apply(fa)(unit(f)) def map2[A,B,C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = apply(fb)(map(fa)(f.curried)) def map3[A,B,C,D](fa: F[A], fb: F[B], fc: F[C])(f: (A, B, C) => D): F[D] = apply(fc)(apply(fb)(apply(fa)(unit(f.curried)))) def map4[A,B,C,D,E](fa: F[A], fb: F[B], fc: F[C], fd: F[D])(f: (A, B, C, D) => E): F[E] = { val ff: (A, B, C) => D => E = (a,b,c) => d => f(a,b,c,d) apply(fd)(map3(fa, fb, fc)(ff)) } def product[G[_]](G: Applicative[G]): Applicative[({type f[x] = (F[x], G[x])})#f] = { val F = this new Applicative[({type f[x] = (F[x], G[x])})#f] { def unit[A](a: => A) = (F.unit(a), G.unit(a)) override def apply[A,B](p: (F[A], G[A]))(fs: (F[A => B], G[A => B])) = (F.apply(p._1)(fs._1), G.apply(p._2)(fs._2)) } } def compose[G[_]](G: Applicative[G]): Applicative[({type f[x] = F[G[x]]})#f] = { val F = this def fab[A, B]: G[A => B] => G[A] => G[B] = (gf: G[A => B]) => (ga: G[A]) => G.apply(ga)(gf) def fg[B, A](f: F[G[A => B]]): F[G[A] => G[B]] = F.map(f)(fab) new Applicative[({type f[x] = F[G[x]]})#f] { def unit[A](a: => A) = F.unit(G.unit(a)) override def apply[A, B](a: F[G[A]])(f: F[G[A => B]]): F[G[B]] = F.apply(a)(fg(f)) } } } object Applicative { implicit val bucketApplicative: Applicative[List] = new Applicative[List] { override def apply[A, B](a: List[A])(f: List[A => B]): List[B] = (a, f) match { case (Nil, _) => Nil case (_, Nil) => Nil case (aa :: as, ff :: fs) => val fab: (A => B) => B = f => f(aa) ff(aa) :: as.map(ff) ::: fs.map(fab) ::: apply(as)(fs) case other => Nil } override def unit[A](a: => A): List[A] = List(a) } implicit val optionApplicative: Applicative[Option] = new Applicative[Option] { override def apply[A, B](a: Option[A])(f: Option[A => B]): Option[B] = (a,f) match { case (Some(a), Some(f)) => Some(f(a)) case _ => None } override def unit[A](a: => A): Option[A] = Some(a) } implicit def eitherApplicative[L] = new Applicative[({ type T[A] = Either[L, A] })#T] { override def apply[A, B](a: Either[L, A])(f: Either[L, A => B]): Either[L, B] = (a, f) match { case (Right(a), Right(f)) => Right(f(a)) case (Left(l), _) => Left(l) case (_, Left(l)) => Left(l) } override def unit[A](a: => A): Either[L, A] = Right(a) } implicit val tryApplicative: Applicative[Try] = new Applicative[Try] { override def apply[A, B](a: Try[A])(f: Try[A => B]): Try[B] = (a, f) match { case (Success(a), Success(f)) => Try(f(a)) case (Failure(ex), _) => Failure(ex) case (_, Failure(ex)) => Failure(ex) } override def unit[A](a: => A): Try[A] = Success(a) } }
Example 112
Source File: Traversable.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import ch08.Model.Bucket import scala.language.{higherKinds, reflectiveCalls} import scala.util.{Failure, Success, Try} import scala.{Traversable => _} trait Traversable[F[_]] extends Functor[F] { def traverse[A,B,G[_]: Applicative](a: F[A])(f: A => G[B]): G[F[B]] def sequence[A,G[_]: Applicative](a: F[G[A]]): G[F[A]] = traverse(a)(identity) implicit def compose[H[_]](implicit H: Traversable[H]): Traversable[({type f[x] = F[H[x]]})#f] = { val F = this new Traversable[({type f[x] = F[H[x]]})#f] { override def traverse[A, B, G[_] : Applicative](fa: F[H[A]])(f: A => G[B]) = F.traverse(fa)((ga: H[A]) => H.traverse(ga)(f)) override def map[A, B](in: F[H[A]])(f: A => B): F[H[B]] = F.map(in)((ga: H[A]) => H.map(ga)(f)) } } } object Traversable { implicit val bucketTraversable = new Traversable[Bucket] { override def map[A, B](in: Bucket[A])(f: A => B): Bucket[B] = Functor.bucketFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Bucket[A])(f: A => G[B]): G[Bucket[B]] = { val G = implicitly[Applicative[G]] a.foldRight(G.unit(List[B]()))((aa, fbs) => G.map2(f(aa), fbs)(_ :: _)) } } implicit val optionTraversable = new Traversable[Option] { override def map[A, B](in: Option[A])(f: A => B): Option[B] = Functor.optionFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Option[A])(f: A => G[B]): G[Option[B]] = { val G = implicitly[Applicative[G]] a match { case Some(s) => G.map(f(s))(Some.apply) case None => G.unit(None) } } } implicit val tryTraversable = new Traversable[Try] { override def map[A, B](in: Try[A])(f: A => B): Try[B] = Functor.tryFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Try[A])(f: A => G[B]): G[Try[B]] = { val G = implicitly[Applicative[G]] a match { case Success(s) => G.map(f(s))(Success.apply) case Failure(ex) => G.unit(Failure(ex)) // re-wrap the ex to change the type of Failure } } } implicit def eitherTraversable[L] = new Traversable[({ type T[A] = Either[L, A] })#T] { override def map[A, B](in: Either[L, A])(f: A => B): Either[L, B] = Functor.eitherFunctor[L].map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Either[L, A])(f: A => G[B]): G[Either[L, B]] = { val G = implicitly[Applicative[G]] a match { case Right(s) => G.map(f(s))(Right.apply) case Left(l) => G.unit(Left(l)) // re-wrap the l to change the type of Failure } } } }
Example 113
Source File: json.scala From picopickle with MIT License | 5 votes |
package io.github.netvl.picopickle.backends.jawn import io.github.netvl.picopickle._ import scala.util.{Try, Success, Failure} trait JsonBackendComponent extends BackendComponent { override val backend = JsonAst.Backend } trait JsonExceptionsComponent extends ExceptionsComponent { this: BackendComponent => case class JsonParseException(message: String, cause: Throwable) extends BaseException(message, cause) } trait JsonStringSerializationComponent { self: Pickler with TypesComponent with JsonBackendComponent with JsonExceptionsComponent => def readAst(str: String): JsonAst.JsonValue = jawn.Parser.parseFromString(str)(JawnFacade) match { case Success(r) => r case Failure(e) => throw JsonParseException(s"invalid JSON: $str", e) } def writeAst(ast: JsonAst.JsonValue): String = JsonRenderer.render(ast) def readString[T: Reader](str: String): T = read[T](readAst(str)) def tryReadString[T: Reader](str: String): Try[T] = Try(readString[T](str)) def writeString[T: Writer](value: T): String = writeAst(write(value)) class JsonSerializer[T: Reader: Writer] extends Serializer[T] { def readString(str: String): T = self.readString[T](str) def tryReadString(str: String): Try[T] = self.tryReadString[T](str) def writeString(value: T): String = self.writeString(value) } override def serializer[T: Reader: Writer]: JsonSerializer[T] = new JsonSerializer[T] } trait JsonPickler extends DefaultPickler with JsonBackendComponent with JsonStringSerializationComponent with JsonExceptionsComponent object JsonPickler extends JsonPickler
Example 114
Source File: PipeToSupport.scala From perf_tester with Apache License 2.0 | 5 votes |
package akka.pattern import language.implicitConversions import scala.concurrent.{ Future, ExecutionContext } import scala.util.{ Failure, Success } import akka.actor.{ Status, ActorRef, Actor } import akka.actor.ActorSelection import java.util.concurrent.CompletionStage import java.util.function.BiConsumer trait PipeToSupport { final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) { def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = { future andThen { case Success(r) ⇒ recipient ! r case Failure(f) ⇒ recipient ! Status.Failure(f) } } def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = { future andThen { case Success(r) ⇒ recipient ! r case Failure(f) ⇒ recipient ! Status.Failure(f) } } def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender) def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = { pipeTo(recipient)(sender) this } def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender) def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = { pipeToSelection(recipient)(sender) this } } final class PipeableCompletionStage[T](val future: CompletionStage[T])(implicit executionContext: ExecutionContext) { def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = { future whenComplete new BiConsumer[T, Throwable] { override def accept(t: T, ex: Throwable) { if (t != null) recipient ! t if (ex != null) recipient ! Status.Failure(ex) } } } def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = { future whenComplete new BiConsumer[T, Throwable] { override def accept(t: T, ex: Throwable) { if (t != null) recipient ! t if (ex != null) recipient ! Status.Failure(ex) } } } def to(recipient: ActorRef): PipeableCompletionStage[T] = to(recipient, Actor.noSender) def to(recipient: ActorRef, sender: ActorRef): PipeableCompletionStage[T] = { pipeTo(recipient)(sender) this } def to(recipient: ActorSelection): PipeableCompletionStage[T] = to(recipient, Actor.noSender) def to(recipient: ActorSelection, sender: ActorRef): PipeableCompletionStage[T] = { pipeToSelection(recipient)(sender) this } } implicit def pipeCompletionStage[T](future: CompletionStage[T])(implicit executionContext: ExecutionContext): PipeableCompletionStage[T] = new PipeableCompletionStage(future) }
Example 115
Source File: HttpTest.scala From scalajs-angulate with MIT License | 5 votes |
// - Project: scalajs-angulate (https://github.com/jokade/scalajs-angulate) // Description: // // Distributed under the MIT License (see included file LICENSE) package test import biz.enef.angulate._ import biz.enef.angulate.core.HttpService import utest._ import scala.scalajs.js import scala.util.{Failure, Success} import js.Dynamic.literal import scala.language.implicitConversions import AnnotatedFunction._ import Module._ object HttpTest extends AngulateTestSuite { override val tests = TestSuite { implicit val module = angular.createModule("test", Seq("ngMockE2E")) module.run ( ($httpBackend: js.Dynamic) => { $httpBackend.whenGET("/ok").respond( literal(id = 200) ) $httpBackend.whenGET("/error").respond(404,"resource not found") $httpBackend.whenPOST("/empty").respond(204) }) val $http = dependency[HttpService]("$http") var ok = false 'onComplete-{ 'success-{ val p = promise() $http.get[Data]("/ok").onComplete { case Success(data) => p.assert( data.id == 200 ) case x => p.fail() } p.future } 'failure-{ val p = promise() $http.get[Data]("/error").onComplete { case Success(_) => p.fail() case Failure(ex) => p.ok() } p.future } 'expectEmptyResponse-{ val p = promise() $http.post[Unit]("/empty").onComplete{ case Success(x) => p.ok() case _ => p.fail() } p.future } } 'onSuccess-{ 'success-{ val p = promise() $http.get[Data]("/ok").onSuccess { data => p.assert( data.id == 200 ) } p.future } 'expectEmptyResponse-{ val p = promise() $http.post[Unit]("/empty").onSuccess( x => p.ok() ) p.future } } } trait Data extends js.Object { def id: Int = js.native } }
Example 116
Source File: JsonEntitiesFromCodecs.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.algebra.playjson import endpoints4s.{Codec, Invalid, Valid, Validated} import play.api.libs.json.{Format, JsPath, Json, JsonValidationError} import scala.util.{Failure, Success, Try} trait JsonEntitiesFromCodecs extends endpoints4s.algebra.JsonEntitiesFromCodecs { //#type-carrier type JsonCodec[A] = Format[A] //#type-carrier def stringCodec[A: Format]: Codec[String, A] = new Codec[String, A] { def decode(from: String): Validated[A] = (Try(Json.parse(from)) match { case Failure(_) => Left(Invalid("Unable to parse entity as JSON")) case Success(a) => Right(a) }).flatMap { json => def showErrors( errors: collection.Seq[ (JsPath, collection.Seq[JsonValidationError]) ] ): Invalid = Invalid( ( for { (path, pathErrors) <- errors.iterator error <- pathErrors } yield s"${error.message} for ${path.toJsonString}" ).toSeq ) Json .fromJson[A](json) .asEither .left .map(showErrors) .map(Valid(_)) }.merge def encode(from: A): String = Json.stringify(Json.toJson(from)) } }
Example 117
Source File: OAuth2Provider.scala From akka-http-oauth2-provider with MIT License | 5 votes |
package scalaoauth2.provider import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.directives.Credentials import scalaoauth2.provider.OAuth2Provider.TokenResponse import spray.json.{JsValue, DefaultJsonProtocol} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} trait OAuth2Provider[U] extends Directives with DefaultJsonProtocol { import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ val oauth2DataHandler: DataHandler[U] val tokenEndpoint: TokenEndpoint def grantResultToTokenResponse(grantResult: GrantHandlerResult[U]): JsValue = OAuth2Provider.tokenResponseFormat.write( TokenResponse( grantResult.tokenType, grantResult.accessToken, grantResult.expiresIn.getOrElse(1L), grantResult.refreshToken.getOrElse("") ) ) def oauth2Authenticator( credentials: Credentials ): Future[Option[AuthInfo[U]]] = credentials match { case Credentials.Provided(token) => oauth2DataHandler.findAccessToken(token).flatMap { case Some(token) => oauth2DataHandler.findAuthInfoByAccessToken(token) case None => Future.successful(None) } case _ => Future.successful(None) } def accessTokenRoute = pathPrefix("oauth") { path("access_token") { post { formFieldMap { fields => onComplete( tokenEndpoint.handleRequest( new AuthorizationRequest( Map(), fields.map(m => m._1 -> Seq(m._2)) ), oauth2DataHandler ) ) { case Success(maybeGrantResponse) => maybeGrantResponse.fold( oauthError => complete(Unauthorized), grantResult => complete(grantResultToTokenResponse(grantResult)) ) case Failure(ex) => complete( InternalServerError, s"An error occurred: ${ex.getMessage}" ) } } } } } } object OAuth2Provider extends DefaultJsonProtocol { case class TokenResponse( token_type: String, access_token: String, expires_in: Long, refresh_token: String ) implicit val tokenResponseFormat = jsonFormat4(TokenResponse) }
Example 118
Source File: GithubService.scala From scabot with Apache License 2.0 | 5 votes |
package scabot
package github
import akka.event.Logging
import scala.util.{Success, Failure}
trait GithubService extends GithubApi {
private lazy val UserRepo = """([^/]+)/(.+)""".r
def notifyProject(ev: ProjectMessage, repository: Repository): String = {
val UserRepo(user, repo) = repository.full_name
val log = s"Processing $ev for $user/$repo"
system.log.info(log)
broadcast(user, repo)(ev)
log
}
def pullRequestEvent(ev: PullRequestEvent): String = ev match {
case PullRequestEvent(action, number, pull_request) =>
notifyProject(ev, ev.pull_request.base.repo)
}
def pushEvent(ev: PushEvent): String = ev match {
case PushEvent(_, _, repository) =>
notifyProject(ev, repository)
}
def issueCommentEvent(ev: IssueCommentEvent): String = ev match {
case IssueCommentEvent(action, issue, comment, repository) =>
notifyProject(ev, repository)
}
def pullRequestReviewCommentEvent(ev: PullRequestReviewCommentEvent): String = ev match {
case PullRequestReviewCommentEvent(action, pull_request, comment, repository) =>
notifyProject(ev, repository)
}
}
Example 119
Source File: ApplicationFeature.scala From CMAK with Apache License 2.0 | 5 votes |
package features import com.typesafe.config.Config import grizzled.slf4j.Logging import kafka.manager.features.KMFeature import scala.util.{Success, Failure, Try} sealed trait ApplicationFeature extends KMFeature case object KMClusterManagerFeature extends ApplicationFeature case object KMTopicManagerFeature extends ApplicationFeature case object KMPreferredReplicaElectionFeature extends ApplicationFeature case object KMScheduleLeaderElectionFeature extends ApplicationFeature case object KMReassignPartitionsFeature extends ApplicationFeature case object KMBootstrapClusterConfigFeature extends ApplicationFeature object ApplicationFeature extends Logging { import scala.reflect.runtime.universe val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader) def from(s: String) : Option[ApplicationFeature] = { Try { val clazz = s"features.$s" val module = runtimeMirror.staticModule(clazz) val obj = runtimeMirror.reflectModule(module) obj.instance match { case f: ApplicationFeature => f case _ => throw new IllegalArgumentException(s"Unknown application feature $s") } } match { case Failure(t) => error(s"Unknown application feature $s") None case Success(f) => Option(f) } } } case class ApplicationFeatures(features: Set[ApplicationFeature]) object ApplicationFeatures extends Logging { lazy val default : List[String] = List( KMClusterManagerFeature, KMTopicManagerFeature, KMPreferredReplicaElectionFeature, KMReassignPartitionsFeature).map(_.getClass.getSimpleName) def getApplicationFeatures(config: Config) : ApplicationFeatures = { import scala.collection.JavaConverters._ val configFeatures: Option[List[String]] = Try(config.getStringList("application.features").asScala.toList).toOption if(configFeatures.isEmpty) { warn(s"application.features not found in conf file, using default values $default") } val f = configFeatures.getOrElse(default).map(ApplicationFeature.from).flatten ApplicationFeatures(f.toSet) } }
Example 120
Source File: ZIODirectives.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.server.{ Directive, Directive1, Route, RouteResult } import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.server.directives.RouteDirectives import akka.http.scaladsl.util.FastFuture._ import zio.{ DefaultRuntime, Task, ZIO } import scala.concurrent.{ Future, Promise } import scala.util.{ Failure, Success } def zioCompleteOrRecoverWith(magnet: ZIOCompleteOrRecoverWithMagnet): Directive1[Throwable] = magnet.directive } object ZIODirectives extends ZIODirectives trait ZIOCompleteOrRecoverWithMagnet { def directive: Directive1[Throwable] } object ZIOCompleteOrRecoverWithMagnet extends ZIODirectives { implicit def apply[T]( task: => Task[T] )(implicit m: ToResponseMarshaller[T]): ZIOCompleteOrRecoverWithMagnet = new ZIOCompleteOrRecoverWithMagnet { override val directive: Directive1[Throwable] = Directive[Tuple1[Throwable]] { inner => ctx => val future = unsafeRunToFuture(task) import ctx.executionContext future.fast.transformWith { case Success(res) => ctx.complete(res) case Failure(error) => inner(Tuple1(error))(ctx) } } } }
Example 121
Source File: package.scala From reactive-cli with Apache License 2.0 | 5 votes |
package com.lightbend.rp.reactivecli import scala.concurrent.{ ExecutionContext, Future, Promise } import scala.util.{ Failure, Success, Try } package object concurrent { implicit val executionContext: ExecutionContext = Platform.executionContext def attempt[T](f: Future[T]): Future[Try[T]] = f .map(Success.apply) .recover { case t: Throwable => Failure(t) } def optionToFuture[T](option: Option[T], failMsg: String): Future[T] = option.fold(Future.failed[T](new NoSuchElementException(failMsg)))(Future.successful) def wrapFutureOption[T](f: Future[T]): Future[Option[T]] = { val p = Promise[Option[T]] f.onComplete { case Failure(f) => p.success(None) case Success(s) => p.success(Some(s)) } p.future } }
Example 122
Source File: SimpleHttpResponse.scala From RosHTTP with MIT License | 5 votes |
package fr.hmil.roshttp.response import java.nio.ByteBuffer import fr.hmil.roshttp.BackendConfig import fr.hmil.roshttp.exceptions.ResponseException import fr.hmil.roshttp.util.{HeaderMap, Utils} import monix.execution.Scheduler import monix.reactive.Observable import scala.collection.mutable import scala.concurrent.{Future, Promise} import scala.util.{Failure, Success} class SimpleHttpResponse( val statusCode: Int, val headers: HeaderMap[String], val body: String) extends HttpResponse object SimpleHttpResponse extends HttpResponseFactory[SimpleHttpResponse] { override def apply( header: HttpResponseHeader, bodyStream: Observable[ByteBuffer], config: BackendConfig) (implicit scheduler: Scheduler): Future[SimpleHttpResponse] = { val charset = Utils.charsetFromContentType(header.headers.getOrElse("content-type", null)) val buffers = mutable.Queue[ByteBuffer]() val promise = Promise[SimpleHttpResponse]() val streamCollector = bodyStream. foreach(elem => buffers.enqueue(elem)). map({_ => val body = recomposeBody(buffers, config.maxChunkSize, charset) new SimpleHttpResponse(header.statusCode, header.headers, body) }) streamCollector.onComplete({ case res:Success[SimpleHttpResponse] => promise.trySuccess(res.value) case e:Failure[_] => promise.tryFailure(new ResponseException(e.exception, header)) }) promise.future } private def recomposeBody(seq: mutable.Queue[ByteBuffer], maxChunkSize: Int, charset: String): String = { // Allocate maximum expected body length val buffer = ByteBuffer.allocate(seq.length * maxChunkSize) val totalBytes = seq.foldLeft(0)({ (count, chunk) => buffer.put(chunk) count + chunk.limit() }) buffer.limit(totalBytes) Utils.getStringFromBuffer(buffer, charset) } }
Example 123
Source File: CanDropCoreSchema.scala From warp-core with MIT License | 5 votes |
package com.workday.warp.persistence import com.workday.warp.persistence.Tables.profile.api._ import org.pmw.tinylog.Logger import scala.util.{Failure, Success} @throws[RuntimeException]("when there is a database error other than relating to non-existing schema") def dropSchema(): Unit = { val action = this.getMySQLDbName match { case Some(name) => sql"drop schema #$name".asUpdate case None => Tables.schema.drop } this.trySynchronously(action) match { case Success(_) => Logger.info("dropped schema") // if we get errors about tables not existing, its likely because the schema doesn't exist to begin with. // the exception messages for mysql and h2 are slightly different and we need to match both. case Failure(exception) if exception.getMessage matches "Table '.*' doesn't exist" => Logger.trace("schema does not exist") // note that java regex .* won't match line terminators case Failure(exception) if exception.getMessage matches "Table \".*\" not found; SQL statement:\n.*" => Logger.trace("schema does not exist") case Failure(exception) => throw exception } } }
Example 124
Source File: StringPredicate.scala From Scalaprof with GNU General Public License v2.0 | 5 votes |
package com.phasmid.hedge_fund.rules import scala.util.Try import scala.util._ import scala.util.Failure case class StringPredicate(variable: String, operator: Operator[String], value: String) extends Predicate { def apply(candidate: Candidate): Either[Throwable, Boolean] = candidate(variable) match { case Some(x) => Try { operator(x.toString, value) } match { case Success(v) => Right(v) case Failure(f) => Left(f) } case _ => Left(new Exception(s"variable $variable not found in $candidate")) } } object StringPredicate { def apply(variable: String, operator: String, value: String): StringPredicate = new StringPredicate(variable, Operator.createText(operator), value) }
Example 125
Source File: NumberPredicate.scala From Scalaprof with GNU General Public License v2.0 | 5 votes |
package com.phasmid.hedge_fund.rules import scala.util.Try import scala.util._ import scala.util.Failure case class NumberPredicate(variable: String, operator: Operator[Double], value: Double) extends Predicate { def apply(candidate: Candidate): Either[Throwable, Boolean] = candidate(variable) match { case Some(x) => Try { operate(x, operator, value) } match { case Success(v) => Right(v) case Failure(f) => Left(f) } case _ => Left(new Exception(s"variable $variable not found in $candidate")) } // CONSIDER Moving this into Operator class def operate(x: Any, operator: Operator[Double], value: Double): Boolean = { x match { case y: Double => operator(y, value) case y: Int => operator(y, value) case y: String => operator(y.toDouble, value) case _ => throw new Exception(s"variable $variable cannot be for operator $operator") } } } object NumberPredicate { def apply(variable: String, operator: String, value: Double): NumberPredicate = new NumberPredicate(variable, Operator.createNumeric(operator), value) def apply(variable: String, operator: Operator[Double], value: String): NumberPredicate = new NumberPredicate(variable, operator, value.toDouble) def apply(variable: String, operator: String, value: String): NumberPredicate = apply(variable, Operator.createNumeric(operator), value) def apply(predicate: String): NumberPredicate = { val rPredicate = """^\s*(\w+)\s*([=<>]{1,2})\s*(-?[0-9]+\.?[0-9]*)\s*$""".r predicate match { case rPredicate(v, o, n) => apply(v, o, n) case _ => throw new Exception(s"predicate: $predicate is malformed") } } }
Example 126
Source File: Newton.scala From Scalaprof with GNU General Public License v2.0 | 5 votes |
package edu.neu.coe.csye._7200 import scala.annotation.tailrec import scala.util.{Failure, Success, Try} case class Newton(f: Double => Double, dfbydx: Double => Double) { private def step(x: Double, y: Double) = x - y / dfbydx(x) def solve(tries: Int, threshold: Double, initial: Double): Try[Double] = { @tailrec def inner(r: Double, n: Int): Try[Double] = { val y = f(r) if (math.abs(y) < threshold) Success(r) else if (n == 0) Failure(new Exception("failed to converge")) else inner(step(r, y), n - 1) } inner(initial, tries) } }
Example 127
Source File: CallbackTracer.scala From cassandra-util with Apache License 2.0 | 5 votes |
package com.protectwise.cql.tracing import com.protectwise.cql.tracing.CQLTracer.CQLTraceFork import scala.concurrent.{ExecutionContext, Future} import scala.util.{Success, Failure, Try} class CallbackTracer(callback: CQLTrace[_, _] => Unit) extends CQLTracer { class CallbackTracerFork[D](data: D) extends CQLTraceFork { def apply[R](f: => R): R = { val startTime = System.currentTimeMillis() val result = Try(f) callback(CQLTrace(data, startTime, System.currentTimeMillis(), result)) result match { case Success(r) => r case Failure(e) => throw e } } def apply[R](f: Future[R])(implicit ec: ExecutionContext): Future[R] = { val startTime = System.currentTimeMillis() f andThen { case result => callback(CQLTrace(data, startTime, System.currentTimeMillis(), result)) } } } def apply[D](data: D) = new CallbackTracerFork(data) }
Example 128
Source File: FutureTrySpec.scala From scala-common with Apache License 2.0 | 5 votes |
import com.softwaremill.futuretry._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.matchers.must.Matchers import scala.concurrent.duration.Duration import scala.concurrent.{Future, Await, Promise} import scala.util.{Failure, Success, Try} class FutureTrySpec extends AnyFlatSpec with Matchers with TableDrivenPropertyChecks with ScalaFutures { import scala.concurrent.ExecutionContext.Implicits.global "tried" must "convert a successful result into a Success" in { val p = Promise[String] p.complete(Try("a")) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Success("a")) } it must "convert an exceptional result into a Failure" in { val p = Promise[String] val exception = new RuntimeException("blah") p.complete(Try(throw exception)) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Failure(exception)) } "transform" must "correctly transform between all Try variants in" in { val exception = new RuntimeException("bloh") val scenarios = Table[Try[String], Try[String] => Try[String], Try[String]] ( ("original value", "transform", "expected output"), (Success("a"), identity[Try[String]], Success("a")), (Failure(exception), (x: Try[String]) => x match { case Failure(e) => Success(e.toString); case _ => ??? }, Success(exception.toString)), (Success("a"), (x: Try[String]) => x match { case Success(_) => Failure(exception); case _ => ??? }, Failure(exception)), (Failure(exception), identity[Try[String]], Failure(exception)) ) forAll(scenarios) { (orgValue, f, output) => { val p = Promise[String] p.complete(orgValue) val transformedFuture = p.future.transformTry(f) transformedFuture.tried.futureValue must be(output) } } } }
Example 129
Source File: Lambda.scala From aws-lambda-scala with MIT License | 5 votes |
package io.github.mkotsur.aws.handler import java.io.{InputStream, OutputStream} import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler} import io.circe.generic.auto._ import io.github.mkotsur.aws.codecs._ import io.github.mkotsur.aws.proxy.{ProxyRequest, ProxyResponse} import org.slf4j.LoggerFactory import cats.syntax.either.catsSyntaxEither import io.github.mkotsur.aws.handler.Lambda.HandleResult import scala.language.{higherKinds, postfixOps} import scala.util.{Failure, Success, Try} object Lambda extends AllCodec with ProxyRequestCodec { type Handle[I, O] = (I, Context) => HandleResult[O] type HandleResult[O] = Either[Throwable, O] type Proxy[I, O] = Lambda[ProxyRequest[I], ProxyResponse[O]] object Proxy { type Handle[I, O] = (ProxyRequest[I], Context) => HandleResult[O] type HandleResult[O] = Either[Throwable, ProxyResponse[O]] private type CanDecodeProxyRequest[A] = CanDecode[ProxyRequest[A]] private type CanEncodeProxyRequest[A] = CanEncode[ProxyResponse[A]] def instance[I: CanDecodeProxyRequest, O: CanEncodeProxyRequest]( doHandle: Proxy.Handle[I, O]): Lambda[ProxyRequest[I], ProxyResponse[O]] = new Lambda.Proxy[I, O] { override protected def handle(i: ProxyRequest[I], c: Context) = doHandle(i, c) } } def instance[I: CanDecode, O: CanEncode](doHandle: Handle[I, O]) = new Lambda[I, O] { override protected def handle(i: I, c: Context): Either[Throwable, O] = { super.handle(i, c) doHandle(i, c) } } type ReadStream[I] = InputStream => Either[Throwable, I] type ObjectHandler[I, O] = I => Either[Throwable, O] type WriteStream[O] = (OutputStream, Either[Throwable, O], Context) => Either[Throwable, Unit] private val logger = LoggerFactory.getLogger(getClass) } abstract class Lambda[I: CanDecode, O: CanEncode] extends RequestStreamHandler { final def handle(input: InputStream, output: OutputStream, context: Context): Unit = handleRequest(input, output, context) // This function will ultimately be used as the external handler final def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = { val read = implicitly[CanDecode[I]].readStream(input) val handled = read.flatMap { input => Try(handle(input, context)) match { case Success(v) => v case Failure(e) => Lambda.logger.error(s"Error while executing lambda handler: ${e.getMessage}", e) Left(e) } } val written = implicitly[CanEncode[O]].writeStream(output, handled, context) output.close() written.left.foreach(e => throw e) } }
Example 130
Source File: FutureCodec.scala From aws-lambda-scala with MIT License | 5 votes |
package io.github.mkotsur.aws.codecs import java.io.ByteArrayOutputStream import java.nio.charset.Charset import io.circe.Encoder import io.github.mkotsur.aws.handler.CanEncode import io.github.mkotsur.aws.proxy.ProxyResponse import io.circe.generic.auto._ import io.circe.syntax._ import cats.syntax.either.catsSyntaxEither import scala.concurrent.{Await, Future} import scala.concurrent.duration._ import scala.language.postfixOps import scala.util.{Failure, Success, Try} private[aws] trait FutureCodec { implicit def canEncodeFuture[I: Encoder](implicit canEncode: Encoder[I]) = CanEncode.instance[Future[I]]((os, responseEither, ctx) => { (for { response <- responseEither.toTry futureResult <- Try(Await.result(response, ctx.getRemainingTimeInMillis millis)) json <- Try(canEncode(futureResult).noSpaces.getBytes) _ <- Try(os.write(json)) } yield { () }) match { case Success(v) => Right(v) case Failure(e) => Left(e) } }) implicit def canEncodeProxyResponse[T](implicit canEncode: CanEncode[T]) = CanEncode.instance[ProxyResponse[T]]( (output, proxyResponseEither, ctx) => { def writeBody(bodyOption: Option[T]): Either[Throwable, Option[String]] = bodyOption match { case None => Right(None) case Some(body) => val os = new ByteArrayOutputStream() val result = canEncode.writeStream(os, Right(body), ctx) os.close() result.map(_ => Some(os.toString())) } val proxyResposeOrError = for { proxyResponse <- proxyResponseEither bodyOption <- writeBody(proxyResponse.body) } yield ProxyResponse[String]( proxyResponse.statusCode, proxyResponse.headers, bodyOption ) val response = proxyResposeOrError match { case Right(proxyRespose) => proxyRespose case Left(e) => ProxyResponse[String]( 500, Some(Map("Content-Type" -> s"text/plain; charset=${Charset.defaultCharset().name()}")), Some(e.getMessage) ) } output.write(response.asJson.noSpaces.getBytes) Right(()) } ) }
Example 131
Source File: DeepsenseBuildInfoPlugin.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
import scala.util.{Failure, Success, Try} import sbt.Keys._ import sbt._ import sbtbuildinfo.BuildInfoKey.Entry import sbtbuildinfo.{BuildInfoKey, BuildInfoPlugin} object DeepsenseBuildInfoPlugin extends AutoPlugin { override def requires: Plugins = BuildInfoPlugin def parseVersionString(versionString: String): (Int, Int, Int, String) = { // <number>.<number>.<number><optional_rest> val splitRegex = """([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9].*)?""".r Try { versionString match { case splitRegex(maj, min, fix, rest) => (maj.toInt, min.toInt, fix.toInt, Option(rest).getOrElse("")) case _ => throw new IllegalArgumentException( s"Version must conform to regex given by string ${splitRegex.toString()}") } } match { case Success(versionTuple) => versionTuple case Failure(nfe: NumberFormatException) => throw new IllegalArgumentException("Version must start with X.Y.Z, " + "where X, Y and Z are non negative integers!") case Failure(e) => throw e } } val buildInfoKeysSetting: Def.Initialize[Seq[Entry[_]]] = Def.setting { lazy val (maj, min, fix, rest) = parseVersionString(version.value) Seq( BuildInfoKey.action("gitCommitId") { Process("git rev-parse HEAD").lines.head }, "apiVersionMajor" -> maj, "apiVersionMinor" -> min, "apiVersionPatch" -> fix, "apiVersionRest" -> rest ) } override def projectSettings: Seq[Def.Setting[_]] = Seq( BuildInfoPlugin.autoImport.buildInfoKeys ++= buildInfoKeysSetting.value ) }
Example 132
Source File: MainPage.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package pages import components.AbstractComponent import japgolly.scalajs.react._ import japgolly.scalajs.react.component.Scala.Unmounted import japgolly.scalajs.react.vdom.html_<^._ import model._ import org.scalajs.dom.raw.HTMLButtonElement import service.SampleModelObjectRESTClient import typingsJapgolly.semanticDashUiDashReact.components._ import typingsJapgolly.semanticDashUiDashReact.distCommonjsElementsButtonButtonMod.ButtonProps import scala.util.{ Failure, Success } object MainPage extends AbstractComponent { case class State(objects: Seq[SampleModelObject] = Seq.empty) import util.ModelPickler._ class Backend($ : BackendScope[_, State]) { def init(state: State): Callback = Callback.empty def refresh(state: State): Callback = SampleModelObjectRESTClient.remoteSystem.search(None).completeWith { case Success(objects) => $.modState(_.copy(objects = objects)) case Failure(t) => t.printStackTrace() Callback.empty //TODO do something else with the failure here } def onAddNewObject(event: ReactMouseEventFrom[HTMLButtonElement], data: ButtonProps): Callback = Callback.alert( "Clicked on 'Add New object'... did you expect something else? hey, I can't write everything for you!" ) def render(state: State): VdomElement = appContext.consume { appState => <.div( Table()( TableHeader()( TableRow()( TableHeaderCell()("Id"), TableHeaderCell()("Name") ) ), TableBody()( state.objects.toVdomArray { obj => TableRow()( TableCell()(obj.id), TableCell()(obj.name) ) } ) ), Button(onClick = onAddNewObject _)("Add new object") ) } } private val component = ScalaComponent .builder[Unit]("MainPage") .initialState(State()) .renderBackend[Backend] .componentDidMount($ => $.backend.init($.state) >> $.backend.refresh($.state)) .build def apply(): Unmounted[Unit, State, Backend] = component() }
Example 133
Source File: KafkaConsumerSpec.scala From scala-kafka-client with MIT License | 5 votes |
package cakesolutions.kafka import org.apache.kafka.clients.consumer.ConsumerRecords import org.scalatest.concurrent.Waiters.Waiter import scala.concurrent.ExecutionContext.Implicits.global import org.slf4j.LoggerFactory import scala.collection.JavaConverters._ import scala.util.{Failure, Random, Success} class KafkaConsumerSpec extends KafkaIntSpec { private def randomString: String = Random.alphanumeric.take(5).mkString("") private val log = LoggerFactory.getLogger(getClass) private val serializer = (msg: String) => msg.getBytes private val deserializer = (bytes: Array[Byte]) => new String(bytes) val consumerConfig: KafkaConsumer.Conf[String, String] = { KafkaConsumer.Conf(KafkaDeserializer(deserializer), KafkaDeserializer(deserializer), bootstrapServers = s"localhost:$kafkaPort", groupId = randomString, enableAutoCommit = false) } val producerConfig: KafkaProducer.Conf[String, String] = { KafkaProducer.Conf(KafkaSerializer(serializer), KafkaSerializer(serializer), bootstrapServers = s"localhost:$kafkaPort") } "KafkaConsumer and KafkaProducer with Function serializers" should "deliver and consume a message" in { val topic = randomString log.info(s"Using topic [$topic] and kafka port [$kafkaPort]") val producer = KafkaProducer(producerConfig) val consumer = KafkaConsumer(consumerConfig) consumer.subscribe(List(topic).asJava) val records1 = consumer.poll(1000) records1.count() shouldEqual 0 log.info("Kafka producer connecting on port: [{}]", kafkaPort) producer.send(KafkaProducerRecord(topic, Some("key"), "value")) producer.flush() val records2: ConsumerRecords[String, String] = consumer.poll(1000) records2.count() shouldEqual 1 producer.close() consumer.close() } "Kafka producer with bad serializer" should "return a failed future" in { val w = new Waiter val topic = randomString log.info(s"Using topic [$topic] and kafka port [$kafkaPort]") val badSerializer = (msg: String) => { throw new Exception("Serialization failed") } val producerConfig = KafkaProducer.Conf( KafkaSerializer(serializer), KafkaSerializer(badSerializer), bootstrapServers = s"localhost:$kafkaPort" ) val producer = KafkaProducer(producerConfig) log.info("Kafka producer connecting on port: [{}]", kafkaPort) val future = producer.send(KafkaProducerRecord(topic, Some("key"), "value")) future.onComplete { case Success(_) => case Failure(_) => w.dismiss() } w.await() producer.close() } }
Example 134
Source File: ItemName.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model.names import com.flaminem.flamy.model.exceptions.FlamyException import org.rogach.scallop.ValueConverter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.{higherKinds, implicitConversions} import scala.reflect.runtime.universe._ import scala.util.{Failure, Success, Try} def tryParse(s: String): Try[ItemName] = { Try{ SchemaName.parse(s) .orElse{ TableName.parse(s) } .orElse{ TablePartitionName.parse(s) } .getOrElse { throw new IllegalArgumentException("Wrong item name : " + s) } } } def tryParse(s: String, allowedTypes: Set[Class[_]]): Try[ItemName] = { tryParse(s).flatMap { case item if allowedTypes.contains(item.getClass) => Success(item) case item => Failure( new IllegalArgumentException( s"Item $item is a ${item.getClass.getSimpleName}, " + s"but only the following item types are allowed: ${allowedTypes.map{_.getSimpleName}.mkString("[", ", ", "]")}" ) ) } } implicit def fromStringTraversableLike[T[Z] <: TraversableLike[Z, T[Z]]] (l: T[String])(implicit bf: CanBuildFrom[T[String], ItemName, T[ItemName]]) : T[ItemName] = { l.map{tryParse(_).get} } private def fromArgs(args: Seq[String]): Either[String, Option[List[ItemName]]] = { val tries: Seq[Try[ItemName]] = args.map{tryParse} if(tries.forall{_.isSuccess}){ Right(Some(tries.map{_.get}.toList)) } else { val firstFailureIndex = tries.indexWhere(_.isFailure) Left(s"Could not parse the item name ${args(firstFailureIndex)}") } } implicit val scallopConverterList: ValueConverter[List[ItemName]] = { new ValueConverter[List[ItemName]] { override def parse(s: List[(String, List[String])]): Either[String, Option[List[ItemName]]] = { s match { case l if l.nonEmpty => fromArgs(l.flatMap{_._2}) case Nil => Right(None) } } override val tag: TypeTag[List[ItemName]] = typeTag[List[ItemName]] override val argType = org.rogach.scallop.ArgType.LIST } } }
Example 135
Source File: MonadError.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.monad import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} trait MonadError[F[_]] { def unit[T](t: T): F[T] def map[T, T2](fa: F[T])(f: T => T2): F[T2] def flatMap[T, T2](fa: F[T])(f: T => F[T2]): F[T2] def error[T](t: Throwable): F[T] protected def handleWrappedError[T](rt: F[T])(h: PartialFunction[Throwable, F[T]]): F[T] def handleError[T](rt: => F[T])(h: PartialFunction[Throwable, F[T]]): F[T] = { Try(rt) match { case Success(v) => handleWrappedError(v)(h) case Failure(e) if h.isDefinedAt(e) => h(e) case Failure(e) => error(e) } } } object MonadError { def recoverErrors[I, E, O, F[_]]( f: I => F[O] )(implicit eClassTag: ClassTag[E], eIsThrowable: E <:< Throwable): MonadError[F] => I => F[Either[E, O]] = { implicit monad => i => import sttp.tapir.monad.syntax._ monad.handleError(f(i).map(Right(_): Either[E, O])) { case e if eClassTag.runtimeClass.isInstance(e) => (Left(e.asInstanceOf[E]): Either[E, O]).unit } } } class FutureMonadError(implicit ec: ExecutionContext) extends MonadError[Future] { override def unit[T](t: T): Future[T] = Future.successful(t) override def map[T, T2](fa: Future[T])(f: (T) => T2): Future[T2] = fa.map(f) override def flatMap[T, T2](fa: Future[T])(f: (T) => Future[T2]): Future[T2] = fa.flatMap(f) override def error[T](t: Throwable): Future[T] = Future.failed(t) override protected def handleWrappedError[T](rt: Future[T])(h: PartialFunction[Throwable, Future[T]]): Future[T] = rt.recoverWith(h) }
Example 136
Source File: EndpointToAkkaServer.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.server.akkahttp import akka.http.scaladsl.model.{MediaType => _} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server._ import akka.http.scaladsl.server.directives.RouteDirectives import akka.http.scaladsl.server.util.{Tuple => AkkaTuple} import sttp.tapir._ import sttp.tapir.monad.FutureMonadError import sttp.tapir.server.{ServerDefaults, ServerEndpoint} import sttp.tapir.typelevel.ParamsToTuple import scala.concurrent.Future import scala.util.{Failure, Success} class EndpointToAkkaServer(serverOptions: AkkaHttpServerOptions) { def toDirective[I, E, O, T](e: Endpoint[I, E, O, AkkaStream])(implicit paramsToTuple: ParamsToTuple.Aux[I, T]): Directive[T] = { implicit val tIsAkkaTuple: AkkaTuple[T] = AkkaTuple.yes toDirective1(e).flatMap { values => tprovide(paramsToTuple.toTuple(values)) } } def toRoute[I, E, O](se: ServerEndpoint[I, E, O, AkkaStream, Future]): Route = { toDirective1(se.endpoint) { values => extractLog { log => mapResponse(resp => { serverOptions.logRequestHandling.requestHandled(se.endpoint, resp.status.intValue())(log); resp }) { extractExecutionContext { ec => onComplete(se.logic(new FutureMonadError()(ec))(values)) { case Success(Left(v)) => OutputToAkkaRoute(ServerDefaults.StatusCodes.error.code, se.endpoint.errorOutput, v) case Success(Right(v)) => OutputToAkkaRoute(ServerDefaults.StatusCodes.success.code, se.endpoint.output, v) case Failure(e) => serverOptions.logRequestHandling.logicException(se.endpoint, e)(log) throw e } } } } } } def toRoute(serverEndpoints: List[ServerEndpoint[_, _, _, AkkaStream, Future]]): Route = { serverEndpoints.map(se => toRoute(se)).foldLeft(RouteDirectives.reject: Route)(_ ~ _) } private def toDirective1[I, E, O](e: Endpoint[I, E, O, AkkaStream]): Directive1[I] = new EndpointToAkkaDirective(serverOptions)(e) }
Example 137
Source File: TapirJsonSpray.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.json.spray import spray.json._ import sttp.tapir.Codec.JsonCodec import sttp.tapir.DecodeResult.{Error, Value} import sttp.tapir.SchemaType._ import sttp.tapir._ import scala.util.{Failure, Success, Try} trait TapirJsonSpray { def jsonBody[T: JsonFormat: Schema: Validator]: EndpointIO.Body[String, T] = anyFromUtf8StringBody(jsonFormatCodec[T]) implicit def jsonFormatCodec[T: JsonFormat: Schema: Validator]: JsonCodec[T] = Codec.json { s => Try(s.parseJson.convertTo[T]) match { case Success(v) => Value(v) case Failure(e) => Error("spray json decoder failed", e) } } { t => t.toJson.toString() } implicit val schemaForSprayJsValue: Schema[JsValue] = Schema( SProduct( SObjectInfo("spray.json.JsValue"), List.empty ) ) }
Example 138
Source File: TapirJsonuPickle.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.json.upickle import scala.util.{Try, Success, Failure} import sttp.tapir._ import sttp.tapir.Codec.JsonCodec import sttp.tapir.DecodeResult.{Error, Value} import upickle.default.{ReadWriter, read, write} trait TapirJsonuPickle { def jsonBody[T: ReadWriter: Schema: Validator]: EndpointIO.Body[String, T] = anyFromUtf8StringBody(readWriterCodec[T]) implicit def readWriterCodec[T: ReadWriter: Schema: Validator]: JsonCodec[T] = Codec.json[T] { s => Try(read[T](s)) match { case Success(v) => Value(v) case Failure(e) => Error("upickle decoder failed", e) } } { t => write(t) } }
Example 139
Source File: TapirJsonJsoniter.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.json.jsoniter import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec import sttp.tapir.Codec.JsonCodec import sttp.tapir.DecodeResult.{Error, Value} import sttp.tapir.{EndpointIO, Schema, Validator, anyFromUtf8StringBody} import com.github.plokhotnyuk.jsoniter_scala.core._ import scala.util.{Failure, Success, Try} trait TapirJsonJsoniter { def jsonBody[T: JsonValueCodec: Schema: Validator]: EndpointIO.Body[String, T] = anyFromUtf8StringBody(jsoniterCodec[T]) implicit def jsoniterCodec[T: JsonValueCodec: Schema: Validator]: JsonCodec[T] = sttp.tapir.Codec.json { s => Try(readFromString[T](s)) match { case Failure(error) => Error(s, error) case Success(v) => Value(v) } } { t => writeToString[T](t) } }
Example 140
Source File: TwitterSinkTask.scala From kafka-connect-twitter with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.clients.consumer.OffsetAndMetadata import org.apache.kafka.common.TopicPartition import org.apache.kafka.connect.sink.{SinkRecord, SinkTask} import scala.collection.JavaConverters._ import scala.util.{Success, Failure} class TwitterSinkTask extends SinkTask with Logging { var writer: Option[SimpleTwitterWriter] = None override def start(props: util.Map[String, String]): Unit = { val sinkConfig = new TwitterSinkConfig(props) writer = Some(new TwitterWriter( sinkConfig.getString(TwitterSinkConfig.CONSUMER_KEY_CONFIG), sinkConfig.getPassword(TwitterSinkConfig.CONSUMER_SECRET_CONFIG).value, sinkConfig.getString(TwitterSinkConfig.TOKEN_CONFIG), sinkConfig.getPassword(TwitterSinkConfig.SECRET_CONFIG).value)) } override def put(records: util.Collection[SinkRecord]): Unit = records.asScala .map(_.value.toString) .map(text => (text, writer match { case Some(writer) => writer.updateStatus(text) case None => Failure(new IllegalStateException("twitter writer is not set")) })) .foreach { case (text, result) => result match { case Success(id) => log.info(s"successfully tweeted `${text}`; got assigned id ${id}") case Failure(err) => log.warn(s"tweeting `${text}` failed: ${err.getMessage}") } } override def stop(): Unit = { } override def flush(map: util.Map[TopicPartition, OffsetAndMetadata]) = { } override def version(): String = "" }
Example 141
Source File: TwitterSourceConnector.scala From kafka-connect-twitter with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.connect.connector.{Task, Connector} import org.apache.kafka.connect.errors.ConnectException import scala.collection.JavaConverters._ import scala.util.{Failure, Try} override def start(props: util.Map[String, String]): Unit = { log.info(s"Starting Twitter source task with ${props.toString}.") configProps = props Try(new TwitterSourceConfig(props)) match { case Failure(f) => throw new ConnectException("Couldn't start Twitter source due to configuration error: " + f.getMessage, f) case _ => } } override def stop() = {} override def version(): String = "" }
Example 142
Source File: OrderSubmission.scala From Scala-High-Performance-Programming with MIT License | 5 votes |
package highperfscala.concurrency.future import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} object OrderSubmission { trait RawOrder trait OrderSubmitted trait ValidatedOrder object ValidatedOrder { def fromRawOrder(o: RawOrder): Option[ValidatedOrder] = None } trait AccountPositions def submitOrder( ec: ExecutionContext, sendToExchange: ValidatedOrder => Future[OrderSubmitted], updatePositions: OrderSubmitted => Future[AccountPositions], o: RawOrder): Unit = { implicit val iec = ec (for { vo <- ValidatedOrder.fromRawOrder(o).fold(Future.failed[ValidatedOrder]( new Exception("Order failed validation")))(Future.successful) os <- sendToExchange(vo) ap <- updatePositions(os) } yield (os, ap)).onComplete { case Success((os, ap)) => // Marshal order submission info to caller case Failure(e) => // Marshal appropriate error response to caller } } def submitOrderWithMetrics( ec: ExecutionContext, sendToExchange: ValidatedOrder => Future[OrderSubmitted], updatePositions: OrderSubmitted => Future[AccountPositions], incrementExchangeErrorCount: () => Unit, o: RawOrder): Unit = { implicit val iec = ec (for { vo <- ValidatedOrder.fromRawOrder(o).fold(Future.failed[ValidatedOrder]( new Exception("Order failed validation")))(Future.successful) os <- { val f = sendToExchange(vo) f.onFailure({ case e => incrementExchangeErrorCount() }) f } ap <- updatePositions(os) } yield (os, ap)).onComplete { case Success((os, ap)) => // Marshal order submission info to caller case Failure(e) => // Marshal appropriate error response to caller } } }
Example 143
Source File: FutureAwaitWithFailFastFnTest.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.concurrent import java.util.concurrent.Executors import com.datamountaineer.streamreactor.connect.concurrent.ExecutorExtension._ import org.scalactic.source.Position import org.scalatest.concurrent.{Eventually, TimeLimits} import org.scalatest.matchers.should.Matchers import org.scalatest.time.{Millis, Span} import org.scalatest.wordspec.AnyWordSpec import scala.util.{Failure, Try} class FutureAwaitWithFailFastFnTest extends AnyWordSpec with Matchers with Eventually with TimeLimits { "FutureAwaitWithFailFastFn" should { "return when all the futures have completed" in { val exec = Executors.newFixedThreadPool(10) val futures = (1 to 5).map(i => exec.submit { Thread.sleep(300) i }) eventually { val result = FutureAwaitWithFailFastFn(exec, futures) exec.isTerminated shouldBe true result shouldBe Seq(1, 2, 3, 4, 5) } } "stop when the first futures times out" in { val exec = Executors.newFixedThreadPool(6) val futures = for (i <- 1 to 10) yield { exec.submit { if (i == 4) { Thread.sleep(1000) sys.error("this task failed.") } else { Thread.sleep(50000) } } } eventually { val t = Try(FutureAwaitWithFailFastFn(exec, futures)) t.isFailure shouldBe true t.asInstanceOf[Failure[_]].exception.getMessage shouldBe "this task failed." exec.isTerminated shouldBe true } } } }
Example 144
Source File: SchemaRegistry.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.schemas import com.typesafe.scalalogging.StrictLogging import io.confluent.kafka.schemaregistry.client.rest.RestService import scala.util.{Failure, Success, Try} import scala.collection.JavaConverters._ def getSubjects(url: String) : List[String] = { val registry = new RestService(url) val schemas: List[String] = Try(registry.getAllSubjects.asScala.toList) match { case Success(s) => s case Failure(f) => { logger.warn("Unable to connect to the Schema registry. An attempt will be made to create the table" + " on receipt of the first records.") List.empty[String] } } schemas.foreach(s=>logger.info(s"Found schemas for $s")) schemas } }
Example 145
Source File: ErrorHandler.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.errors import java.text.SimpleDateFormat import java.util.Date import com.typesafe.scalalogging.StrictLogging import scala.util.{Failure, Success, Try} trait ErrorHandler extends StrictLogging { var errorTracker: Option[ErrorTracker] = None private val dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'Z'") def initialize(maxRetries: Int, errorPolicy: ErrorPolicy): Unit = { errorTracker = Some(ErrorTracker(maxRetries, maxRetries, "", new Date(), errorPolicy)) } def getErrorTrackerRetries() : Int = { errorTracker.get.retries } def errored() : Boolean = { errorTracker.get.retries != errorTracker.get.maxRetries } def handleTry[A](t : Try[A]) : Option[A] = { require(errorTracker.isDefined, "ErrorTracker is not set call. Initialize.") t match { case Success(s) => { //success, check if we had previous errors. if (errorTracker.get.retries != errorTracker.get.maxRetries) { logger.info(s"Recovered from error ${errorTracker.get.lastErrorMessage} at " + s"${dateFormatter.format(errorTracker.get.lastErrorTimestamp)}") } //cleared error resetErrorTracker() Some(s) } case Failure(f) => //decrement the retry count logger.error(s"Encountered error ${f.getMessage}", f) this.errorTracker = Some(decrementErrorTracker(errorTracker.get, f.getMessage)) handleError(f, errorTracker.get.retries, errorTracker.get.policy) None } } def resetErrorTracker() = { errorTracker = Some(ErrorTracker(errorTracker.get.maxRetries, errorTracker.get.maxRetries, "", new Date(), errorTracker.get.policy)) } private def decrementErrorTracker(errorTracker: ErrorTracker, msg: String): ErrorTracker = { if (errorTracker.maxRetries == -1) { ErrorTracker(errorTracker.retries, errorTracker.maxRetries, msg, new Date(), errorTracker.policy) } else { ErrorTracker(errorTracker.retries - 1, errorTracker.maxRetries, msg, new Date(), errorTracker.policy) } } private def handleError(f: Throwable, retries: Int, policy: ErrorPolicy): Unit = { policy.handle(f, true, retries) } }
Example 146
Source File: ConsistencyLevelSettings.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.config.base.traits import com.datamountaineer.streamreactor.connect.config.base.const.TraitConfigConst._ import org.apache.kafka.common.config.ConfigException import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} trait ConsistencyLevelSettings[T <: Enum[T]] extends BaseSettings { def consistencyLevelConstant: String = s"$connectorPrefix.$CONSISTENCY_LEVEL_PROP_SUFFIX" def getConsistencyLevel(implicit ct: ClassTag[T]): Option[T] = { val enum: Class[T] = ct.runtimeClass.asInstanceOf[Class[T]] val consistencyLevel = getString(consistencyLevelConstant) match { case "" => None case other => Try(Enum.valueOf[T](enum, other)) match { case Failure(_) => throw new ConfigException(s"'$other' is not a valid $consistencyLevelConstant. " + s"Available values are:${enum.getEnumConstants.map(_.toString).mkString(",")}") case Success(cl) => Some(cl) } } consistencyLevel } }
Example 147
Source File: FutureAwaitWithFailFastFn.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.concurrent import java.util.concurrent.{ExecutorService, TimeUnit} import com.typesafe.scalalogging.StrictLogging import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.{Await, Future, Promise} import scala.util.Failure object FutureAwaitWithFailFastFn extends StrictLogging { def apply(executorService: ExecutorService, futures: Seq[Future[Unit]], duration: Duration): Unit = { //make sure we ask the executor to shutdown to ensure the process exits executorService.shutdown() val promise = Promise[Boolean]() //stop on the first failure futures.foreach { f => f.failed.foreach { case t => if (promise.tryFailure(t)) { executorService.shutdownNow() } } } val fut = Future.sequence(futures) fut.foreach { case t => if (promise.trySuccess(true)) { val failed = executorService.shutdownNow() if (failed.size() > 0) { logger.error(s"${failed.size()} task have failed.") } } } Await.ready(promise.future, duration).value match { case Some(Failure(t)) => executorService.awaitTermination(1, TimeUnit.MINUTES) //throw the underlying error throw t case _ => executorService.awaitTermination(1, TimeUnit.MINUTES) } } def apply[T](executorService: ExecutorService, futures: Seq[Future[T]], duration: Duration = 1.hours): Seq[T] = { //make sure we ask the executor to shutdown to ensure the process exits executorService.shutdown() val promise = Promise[Boolean]() //stop on the first failure futures.foreach { f => f.failed.foreach { case t => if (promise.tryFailure(t)) { executorService.shutdownNow() } } } val fut = Future.sequence(futures) fut.foreach { case t => if (promise.trySuccess(true)) { val failed = executorService.shutdownNow() if (failed.size() > 0) { logger.error(s"${failed.size()} task have failed.") } } } Await.ready(promise.future, duration).value match { case Some(Failure(t)) => executorService.awaitTermination(1, TimeUnit.MINUTES) //throw the underlying error throw t case _ => executorService.awaitTermination(1, TimeUnit.MINUTES) //return the result from each of the futures Await.result(Future.sequence(futures), 1.minute) } } }
Example 148
Source File: PluginRepoUtils.scala From sbt-idea-plugin with Apache License 2.0 | 5 votes |
package org.jetbrains.sbtidea.download.plugin import org.jetbrains.sbtidea.Keys.IntellijPlugin import org.jetbrains.sbtidea.download._ import org.jetbrains.sbtidea.download.api.InstallContext import sbt.URL import scala.util.{Failure, Success, Try} class PluginRepoUtils(implicit ctx: InstallContext) extends PluginRepoApi { private val baseUrl = "https://plugins.jetbrains.com" def getRemotePluginXmlDescriptor(idea: BuildInfo, pluginId: String, channel: Option[String]): Either[Throwable, PluginDescriptor] = { val chanStr = channel.map(c => s"&channel=$c").getOrElse("") val urlStr = s"$baseUrl/plugins/list?pluginId=$pluginId$chanStr&build=${idea.edition.edition}-${idea.getActualIdeaBuild(ctx.baseDirectory)}" val infoUrl = new URL(urlStr) val res = Try(PluginDescriptor.load(infoUrl)) res match { case Failure(exception) =>Left(exception) case Success(value) => Right(value) } } def getPluginDownloadURL(idea: BuildInfo, pluginInfo: IntellijPlugin.Id): URL = { val urlStr = pluginInfo match { case IntellijPlugin.Id(id, Some(version), Some(channel)) => s"$baseUrl/plugin/download?pluginId=$id&version=$version&channel=$channel" case IntellijPlugin.Id(id, Some(version), None) => s"$baseUrl/plugin/download?pluginId=$id&version=$version" case IntellijPlugin.Id(id, None, Some(channel)) => s"$baseUrl/pluginManager?action=download&id=$id&channel=$channel&build=${idea.edition.edition}-${idea.getActualIdeaBuild(ctx.baseDirectory)}" case IntellijPlugin.Id(id, None, None) => s"$baseUrl/pluginManager?action=download&id=$id&build=${idea.edition.edition}-${idea.getActualIdeaBuild(ctx.baseDirectory)}" } new URL(urlStr) } def getLatestPluginVersion(idea: BuildInfo, pluginId: String, channel: Option[String]): Either[Throwable, String] = getRemotePluginXmlDescriptor(idea, pluginId, channel).right.map(_.version) }
Example 149
Source File: Api.scala From whirlwind-tour-akka-typed with Apache License 2.0 | 5 votes |
package de.heikoseeberger.wtat import akka.actor.{ ActorSystem, Scheduler } import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.model.StatusCodes.{ Conflict, Created, NoContent, NotFound } import akka.http.scaladsl.server.{ Directives, Route } import akka.stream.Materializer import akka.actor.typed.scaladsl.Actor import akka.actor.typed.scaladsl.AskPattern.Askable import akka.actor.typed.{ ActorRef, Behavior } import akka.util.Timeout import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport import java.net.InetSocketAddress import org.apache.logging.log4j.scala.Logging import scala.concurrent.duration.FiniteDuration import scala.util.{ Failure, Success } object Api extends Logging { sealed trait Command private final case object HandleBindFailure extends Command private final case class HandleBound(address: InetSocketAddress) extends Command final val Name = "api" def apply(address: String, port: Int, userRepository: ActorRef[UserRepository.Command], userView: ActorRef[UserView.Command], askTimeout: FiniteDuration)(implicit mat: Materializer): Behavior[Command] = Actor.deferred { context => import akka.actor.typed.scaladsl.adapter._ import context.executionContext implicit val s: ActorSystem = context.system.toUntyped val self = context.self Http() .bindAndHandle(route(userRepository, userView)(askTimeout, context.system.scheduler), address, port) .onComplete { case Failure(_) => self ! HandleBindFailure case Success(ServerBinding(address)) => self ! HandleBound(address) } Actor.immutable { case (_, HandleBindFailure) => logger.error(s"Stopping, because cannot bind to $address:$port!") Actor.stopped case (_, HandleBound(address)) => logger.info(s"Bound to $address") Actor.ignore } } def route( userRepository: ActorRef[UserRepository.Command], userView: ActorRef[UserView.Command] )(implicit askTimeout: Timeout, scheduler: Scheduler): Route = { import Directives._ import ErrorAccumulatingCirceSupport._ import io.circe.generic.auto._ import io.circe.refined._ pathEndOrSingleSlash { get { complete { import UserView._ (userView ? GetUsers).mapTo[Users] } } ~ post { entity(as[User]) { user => import UserRepository._ onSuccess(userRepository ? addUser(user)) { case UsernameTaken(_) => complete(Conflict) case UserAdded(_) => complete(Created) } } } } ~ path(Segment) { username => delete { import UserRepository._ onSuccess(userRepository ? removeUser(username)) { case UsernameUnknown(_) => complete(NotFound) case UserRemoved(_) => complete(NoContent) } } } } }
Example 150
Source File: ClusterTest.scala From exhibitor-mesos-framework with Apache License 2.0 | 5 votes |
package ly.stealth.mesos.exhibitor import org.junit.Assert._ import org.junit.Test import play.api.libs.json.{Writes, Reads} import scala.util.{Failure, Try} class ClusterTest extends MesosTestCase { @Test def expandIds() { val cluster = Cluster() (0 until 5).foreach(i => cluster.addServer(ExhibitorServer("" + i))) Try(cluster.expandIds("")) match { case Failure(t) if t.isInstanceOf[IllegalArgumentException] => case other => fail(other.toString) } assertEquals(List("0"), cluster.expandIds("0")) assertEquals(List("0", "2", "4"), cluster.expandIds("0,2,4")) assertEquals(List("1", "2", "3"), cluster.expandIds("1..3")) assertEquals(List("0", "1", "3", "4"), cluster.expandIds("0..1,3..4")) assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("*")) // duplicates assertEquals(List("0", "1", "2", "3", "4"), cluster.expandIds("0..3,2..4")) // sorting assertEquals(List("2", "3", "4"), cluster.expandIds("4,3,2")) } @Test def loadSave() { val cluster = Cluster() cluster.frameworkId = Some("some id") cluster.save() val loaded = Cluster() loaded.load() assertEquals(cluster.frameworkId, loaded.frameworkId) } }
Example 151
Source File: FetchWithCacheConfigClient.scala From izanami with Apache License 2.0 | 5 votes |
package izanami.configs import java.util.concurrent.TimeUnit import akka.actor.ActorSystem import akka.event.Logging import akka.http.scaladsl.util.FastFuture import akka.stream.Materializer import akka.util.Timeout import com.google.common.cache.{Cache, CacheBuilder} import izanami.Strategy.FetchWithCacheStrategy import izanami.scaladsl._ import izanami._ import play.api.libs.json.Json import scala.concurrent.Future import scala.concurrent.duration.DurationInt import scala.util.{Failure, Success} object FetchWithCacheConfigClient { def apply( clientConfig: ClientConfig, fallback: Configs, underlyingStrategy: ConfigClient, cacheConfig: FetchWithCacheStrategy )(implicit izanamiDispatcher: IzanamiDispatcher, actorSystem: ActorSystem, materializer: Materializer): FetchWithCacheConfigClient = new FetchWithCacheConfigClient(clientConfig, fallback, underlyingStrategy, cacheConfig, underlyingStrategy.cudConfigClient) } private[configs] class FetchWithCacheConfigClient( clientConfig: ClientConfig, fallback: Configs, underlyingStrategy: ConfigClient, cacheConfig: FetchWithCacheStrategy, override val cudConfigClient: CUDConfigClient )(implicit val izanamiDispatcher: IzanamiDispatcher, actorSystem: ActorSystem, val materializer: Materializer) extends ConfigClient { import actorSystem.dispatcher implicit val timeout = Timeout(10.second) private val logger = Logging(actorSystem, this.getClass.getName) private val cache: Cache[String, Seq[Config]] = CacheBuilder .newBuilder() .maximumSize(cacheConfig.maxElement) .expireAfterWrite(cacheConfig.duration.toMillis, TimeUnit.MILLISECONDS) .build[String, Seq[Config]]() override def configs(pattern: Seq[String]): Future[Configs] = { val convertedPattern = Option(pattern).map(_.map(_.replace(".", ":")).mkString(",")).getOrElse("*") Option(cache.getIfPresent(convertedPattern)) match { case Some(configs) => FastFuture.successful(Configs(configs)) case None => val futureConfigs = underlyingStrategy.configs(convertedPattern) futureConfigs.onComplete { case Success(c) => cache.put(convertedPattern, c.configs) case Failure(e) => logger.error(e, "Error fetching configs") } futureConfigs } } override def config(key: String) = { require(key != null, "key should not be null") val convertedKey: String = key.replace(".", ":") Option(cache.getIfPresent(convertedKey)) match { case Some(configs) => FastFuture.successful(configs.find(_.id == convertedKey).map(_.value).getOrElse(Json.obj())) case None => val futureConfig: Future[Configs] = underlyingStrategy.configs(convertedKey) futureConfig.onComplete { case Success(configs) => cache.put(convertedKey, configs.configs) case Failure(e) => logger.error(e, "Error fetching features") } futureConfig .map( _.configs .find(_.id == convertedKey) .map(c => c.value) .getOrElse(Json.obj()) ) } } override def configsSource(pattern: String) = underlyingStrategy.configsSource(pattern) override def configsStream(pattern: String) = underlyingStrategy.configsStream(pattern) }
Example 152
Source File: EventsController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.actor.ActorSystem import controllers.actions.SecuredAuthContext import domains.Domain.Domain import domains.events.{EventStore, EventStoreContext} import play.api.libs.EventSource import play.api.libs.EventSource.{EventDataExtractor, EventIdExtractor, EventNameExtractor} import play.api.libs.json.{JsString, Json} import play.api.mvc.{AbstractController, ActionBuilder, AnyContent, ControllerComponents} import libs.http.HttpContext import akka.stream.scaladsl.Flow import scala.util.Success import scala.util.Failure import libs.logs.IzanamiLogger import java.time.LocalDateTime import play.api.libs.json.JsValue import scala.concurrent.duration.DurationDouble import domains.auth.AuthInfo import domains.Key class EventsController(system: ActorSystem, AuthAction: ActionBuilder[SecuredAuthContext, AnyContent], cc: ControllerComponents)(implicit r: HttpContext[EventStoreContext]) extends AbstractController(cc) { import libs.http._ import domains.events.Events._ import system.dispatcher private implicit val nameExtractor = EventNameExtractor[IzanamiEvent](_ => None) //Some(event.`type`)) private implicit val idExtractor = EventIdExtractor[IzanamiEvent](event => Some(s"${event._id}")) //Some(event.key.key)) private implicit val dataExtractor = EventDataExtractor[IzanamiEvent](event => Json.stringify(event.toJson)) def allEvents(patterns: String, domains: String) = events(domains.split(",").toIndexedSeq, patterns) def eventsForADomain(domain: String, patterns: String) = events(domain.split(",").toIndexedSeq, patterns) val logEvent = Flow[IzanamiEvent].map { event => event } case class KeepAliveEvent() extends IzanamiEvent { val _id: Long = 0 val domain: Domain = domains.Domain.Unknown val authInfo: Option[AuthInfo.Service] = None val key: Key = Key("na") def timestamp: LocalDateTime = LocalDateTime.now() val `type`: String = "KEEP_ALIVE" val payload: JsValue = Json.obj() } val keepAlive = Flow[IzanamiEvent].keepAlive(30.seconds, () => KeepAliveEvent()) // TODO abilitations private def events[T <: IzanamiEvent](domains: Seq[String], patterns: String) = AuthAction.asyncTask[EventStoreContext] { ctx => val allPatterns: Seq[String] = ctx.authorizedPatterns ++ patterns .split(",") .toList val lastEventId = ctx.request.headers.get("Last-Event-ID").map(_.toLong) val allDomains = domains.map(JsString).flatMap(_.validate[Domain].asOpt) EventStore .events(allDomains, allPatterns, lastEventId) .map { source => val eventSource = (source via keepAlive via logEvent via EventSource.flow).watchTermination() { (_, fDone) => fDone.onComplete { case Success(_) => IzanamiLogger.debug("SSE disconnected") case Failure(e) => IzanamiLogger.error("Error during SSE ", e) } fDone } Ok.chunked(eventSource).as("text/event-stream") } } }
Example 153
Source File: TwitterSinkConnector.scala From kafka-connect-twitter with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.connect.connector.Task import org.apache.kafka.connect.errors.ConnectException import org.apache.kafka.connect.sink.SinkConnector import scala.collection.JavaConverters._ import scala.util.{Failure, Try} class TwitterSinkConnector extends SinkConnector with Logging { private var configProps : util.Map[String, String] = null override def start(props: util.Map[String, String]): Unit = { log.info(s"Starting Twitter sink task with ${props.toString}.") configProps = props Try(new TwitterSinkConfig(props)) match { case Failure(f) => throw new ConnectException("Couldn't start TwitterSinkConnector due to configuration error.", f) case _ => } } override def stop(): Unit = {} override def version(): String = "" }
Example 154
Source File: FutureErrorHandling.scala From Scala-High-Performance-Programming with MIT License | 5 votes |
package highperfscala.concurrency.future import scala.concurrent.Future import scala.util.{Failure, Success} import scalaz.{\/-, \/} object FutureErrorHandling { def main(args: Array[String]): Unit = { implicit val context = scala.concurrent.ExecutionContext.global def failedTransform(): Unit = { Future("not-an-integer").map(_.toInt).map(i => { println("Multiplying") i * 2 }) Thread.sleep(1000) } def recoverWith(): Unit = { Future("not-an-integer").map(_.toInt).recover { case _: NumberFormatException => -2 }.map(i => { println("Multiplying") i * 2 }).onComplete { case Success(i) => println(s"Multiplication result = $i") case Failure(e) => println(s"Failed due to ${e.getMessage}") } Thread.sleep(1000) } def disjunction(): Unit = { scalaz.\/.right[Throwable, Int](1).map(_ * 2) } recoverWith() } }
Example 155
Source File: AWSSupport.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.plugins.awssupport import akka.actor.ActorLogging import com.amazonaws.auth.{AWSCredentials, AWSStaticCredentialsProvider} import com.amazonaws.services.support.AWSSupportClientBuilder import com.amazonaws.services.support.model.{CaseDetails, DescribeCasesRequest} import com.sumologic.sumobot.core.aws.AWSAccounts import com.sumologic.sumobot.core.model.IncomingMessage import com.sumologic.sumobot.plugins.BotPlugin import scala.collection.JavaConverters._ import scala.concurrent.ExecutionContext.Implicits.global import scala.util.{Failure, Success, Try} class AWSSupport extends BotPlugin with ActorLogging { case class CaseInAccount(account: String, caseDetails: CaseDetails) private val credentials: Map[String, AWSCredentials] = AWSAccounts.load(context.system.settings.config) private val clients = credentials.map{case (id, credentials) => id -> AWSSupportClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).build()} override protected def help: String = s""" |I can tell you about AWS support tickets. | |list aws cases - List all AWS support tickets. |show aws case <case> - I'll show you more details about that case. """.stripMargin private val CaseDetails = matchText("show aws case (\\d+).*") private val ListCases = matchText("list aws cases") override protected def receiveIncomingMessage: ReceiveIncomingMessage = { case message@IncomingMessage(ListCases(), _, _, _, _, _, _) => message.respondInFuture { msg => val caseList = getAllCases.map(summary(_) + "\n").mkString("\n") msg.message(caseList) } case message@IncomingMessage(CaseDetails(caseId), _, _, _, _, _, _) => message.respondInFuture { msg => log.info(s"Looking for case $caseId") Try(getAllCases) match { case Success(cases) => cases.find(_.caseDetails.getDisplayId == caseId) match { case None => msg.response("Not a known support case.") case Some(cse) => msg.message(details(cse)) } case Failure(e) if e.getMessage.contains("Invalid case ID:") => msg.response(s"Invalid case ID: $caseId") } } } private def getAllCases: Seq[CaseInAccount] = { clients.toSeq.par.flatMap { tpl => val client = tpl._2 val unresolved = client.describeCases(new DescribeCasesRequest()).getCases.asScala.toList val resolved = client.describeCases(new DescribeCasesRequest().withIncludeResolvedCases(true)).getCases.asScala.toList (unresolved ++ resolved).map(CaseInAccount(tpl._1, _)) }.seq } private def summary(cia: CaseInAccount): String = s"*# ${cia.caseDetails.getDisplayId}:* ${cia.caseDetails.getSubject}\n" + s" - account: ${cia.account}, submitted by: ${cia.caseDetails.getSubmittedBy}, status: ${cia.caseDetails.getStatus}" private def details(cia: CaseInAccount): String = { val latest = cia.caseDetails.getRecentCommunications.getCommunications.asScala.head summary(cia) + "\n\n" + s""" |_${latest.getSubmittedBy} at ${latest.getTimeCreated}_ |${latest.getBody} """.stripMargin } }
Example 156
Source File: PluginCollection.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.plugins import akka.actor.{ActorSystem, Props} import akka.event.Logging import com.sumologic.sumobot.core.Bootstrap import com.typesafe.config.ConfigException import scala.util.{Failure, Success, Try} trait PluginCollection { protected def addPlugin(name: String, props: Props)(implicit system: ActorSystem): Unit = { lazy val log = Logging.getLogger(system, this) val property = s"plugins.$name.enabled" Try(system.settings.config.getBoolean(property)) match { case Success(true) => system.actorOf(props, name) case Success(false) => log.debug(s"Plugin $name is disabled.") case Failure(_: ConfigException.Missing) => log.debug(s"Could not find $property. Enabling plugin by default.") system.actorOf(props, name) case Failure(other) => throw other } } def setup(implicit system: ActorSystem): Unit }
Example 157
Source File: ListOfConfigs.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.core.config import com.typesafe.config.{Config, ConfigException} import scala.collection.JavaConverters._ import scala.util.{Failure, Success, Try} object ListOfConfigs { def parse[T](config: Config, path: String)(convert: (String, Config) => T): Map[String, T] = { Try(config.getObject(path).asScala) match { case Success(accounts) => accounts.map { obj => val name = obj._1 name -> convert(name, config.getConfig(path + "." + name)) }.toMap case Failure(e: ConfigException.Missing) => Map.empty case Failure(other) => throw other } } }
Example 158
Source File: WorkflowVersionUtil.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.models.json.workflow import scala.util.{Failure, Success, Try} import spray.json._ import io.deepsense.commons.utils.{Logging, Version} import io.deepsense.models.json.workflow.exceptions._ import io.deepsense.models.workflows._ trait WorkflowVersionUtil extends WorkflowWithResultsJsonProtocol with WorkflowWithVariablesJsonProtocol { this: Logging => def currentVersion: Version def extractVersion(workflow: String): Try[Version] = Try { val workflowJson = workflow.parseJson.asJsObject extractVersion(workflowJson).map(Version(_)).get } def extractVersion(json: JsValue): Try[String] = Try { json.asJsObject.fields("metadata") .asJsObject .fields("apiVersion") .convertTo[String] } val versionedWorkflowReader = new VersionedJsonReader[Workflow] val versionedWorkflowWithResultsReader = new VersionedJsonReader[WorkflowWithResults] val versionedWorkflowWithVariablesReader = new VersionedJsonReader[WorkflowWithVariables] def workflowOrString(stringJson: String): Either[String, Workflow] = parsedOrString(versionedWorkflowReader, stringJson) private def parsedOrString[T](reader: JsonReader[T], stringJson: String): Either[String, T] = { Try { Right(stringJson.parseJson.convertTo[T](reader)) }.recover { case e: WorkflowVersionException => Left(stringJson) }.get } class VersionedJsonReader[T : JsonReader] extends RootJsonReader[T] { override def read(json: JsValue): T = { whenVersionCurrent(json){ _.convertTo[T] } } def whenVersionCurrent(json: JsValue)(f: (JsValue) => T): T = { val versionString = extractVersion(json) match { case Failure(exception) => throw WorkflowVersionNotFoundException(currentVersion) case Success(value) => value } Try(Version(versionString)) match { case Failure(exception) => throw WorkflowVersionFormatException(versionString) case Success(parsedVersion) if parsedVersion.compatibleWith(currentVersion) => f(json) case Success(parsedVersion) if !parsedVersion.compatibleWith(currentVersion) => throw WorkflowVersionNotSupportedException(parsedVersion, currentVersion) } } } }
Example 159
Source File: PythonNotebook.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.deeplang.doperations
import java.io.ByteArrayInputStream
import io.deepsense.commons.utils.Version
import io.deepsense.deeplang.DOperation.Id
import io.deepsense.deeplang.ExecutionContext
import io.deepsense.deeplang.doperables.dataframe.DataFrame
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.reflect.runtime.{universe => ru}
import scala.util.Failure
import io.deepsense.commons.rest.client.NotebookRestClient
case class PythonNotebook()
extends Notebook {
override val id: Id = "e76ca616-0322-47a5-b390-70c9668265dd"
override val name: String = "Python Notebook"
override val description: String = "Creates a Python notebook with access to the DataFrame"
override val since: Version = Version(1, 0, 0)
override val notebookType: String = "python"
override protected def execute(dataFrame: DataFrame)(context: ExecutionContext): Unit = {
context.dataFrameStorage.setInputDataFrame(0, dataFrame.sparkDataFrame)
headlessExecution(context)
}
}
Example 160
Source File: DirectoryListFileFinder.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.commons.utils import java.io.{File, FileNotFoundException, IOException} import scala.util.{Failure, Success, Try} def filePredicate(f: File, desc: Option[String]): Boolean def findFile(): Try[File] = { findFile(None) } def findFile(desc: String): Try[File] = { findFile(Some(desc)) } def findFile(desc: Option[String]): Try[File] = { findPotentialFiles( dirsToSearch, listFilesInDirectory // convert to Try - give a nice message in the exception concerning the dirs, otherwise just Success it ).fold(dirs => Failure( new IOException(s"Unable to list files in dirs: ${dirs.mkString(", ")}") ), Success[Seq[File]] ).flatMap(_.find(filePredicate(_, desc)) .map(Success[File]) .getOrElse(Failure( new FileNotFoundException( s"Unable to find file ${desc.map(_ + " ").getOrElse("")}" + s"in dirs: ${dirsToSearch.mkString(", ")}") )) ) } } object DirectoryListFileFinder { type EitherBadDirsOrFiles = Either[Seq[File], Seq[File]] def findPotentialFiles( dirs: Traversable[File], listFilesInDirectory: File => Option[Seq[File]]): EitherBadDirsOrFiles = { dirs.map { dir => val files = listFilesInDirectory(dir) // if we're unable to list files inside the dir then // let's not lose this information by keeping the dir in Left files.toRight(dir) }.foldLeft(Right(Seq[File]()): EitherBadDirsOrFiles) { case (Left(badDirs), Left(badDir)) => Left(badDir +: badDirs) case (Left(badDirs), Right(_)) => Left(badDirs) case (Right(_), Left(badDir)) => Left(Seq(badDir)) case (Right(files), Right(files2)) => Right(files ++ files2) case _ => ??? // to silence buggy 2.10 non-exhaustive match warning } } }
Example 161
Source File: RetryActor.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.commons.utils import scala.concurrent.{ExecutionContext, Future} import scala.concurrent.duration.FiniteDuration import scala.util.{Failure, Success, Try} import akka.actor.{Actor, ActorRef, Status} class RetryActor[T]( retryInterval: FiniteDuration, retryCountLimit: Int, workCode: => Future[T], workDescription: Option[String]) extends Actor with Logging { import RetryActor._ private implicit val ec: ExecutionContext = context.system.dispatcher override def receive: Receive = { case Trigger => doWork(sender, 0) case Retry(initialSender, retryCount) => doWork(initialSender, retryCount) } val workDescriptionForLogs: String = workDescription.map(" " + _).getOrElse(" some work") private def doWork(initialSender: ActorRef, retryCount: Int): Unit = { workCode.onComplete { case Success(t) => initialSender ! t case Failure(RetriableException(msg, cause)) if retryCount < retryCountLimit => logFailure(msg, cause) logger.info(s"Will retry$workDescriptionForLogs in $retryInterval.") context.system.scheduler.scheduleOnce(retryInterval, self, Retry(initialSender, retryCount + 1)) case Failure(RetriableException(msg, cause)) if retryCount >= retryCountLimit => logFailure(msg, cause) val retryLimitReachedException = RetryLimitReachedException(s"Retry limit of $retryCountLimit reached, last error was $cause", cause) logger.error(s"Retry limit reached for$workDescriptionForLogs.", retryLimitReachedException) initialSender ! Status.Failure(retryLimitReachedException) case Failure(f) => logFailure(f.getMessage, Some(f)) logger.error(s"Unexpected exception when performing$workDescriptionForLogs.", f) initialSender ! Status.Failure(f) } } private def logFailure(msg: String, tOpt: Option[Throwable]): Unit = { val msgText = s"Exception when performing$workDescriptionForLogs. The message was: $msg" tOpt match { case Some(t) => logger.info(msgText, t) case None => logger.info(msgText) } } } object RetryActor { sealed trait Message case object Trigger extends Message case class Retry(initialSender: ActorRef, retryCount: Int) extends Message case class RetryLimitReachedException(msg: String, lastError: Option[Throwable]) extends Exception(msg) case class RetriableException(msg: String, cause: Option[Throwable]) extends Exception(msg, cause.orNull) }
Example 162
Source File: Version.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.commons.utils import scala.util.{Failure, Success, Try} case class Version(major: Int, minor: Int, fix: Int, rest: String) { def humanReadable: String = { Seq(major, minor, fix).mkString(Version.separator.toString) + rest } def compatibleWith(other: Version): Boolean = major == other.major && minor == other.minor } object Version { val separator = '.' def apply(major: Int, minor: Int, fix: Int): Version = { Version(major, minor, fix, "") } def apply(versionString: String): Version = { // <number>.<number>.<number><optional_rest> val splitRegex = """([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9].*)?""".r Try { versionString match { case splitRegex(maj, min, fix, rest) => Version(maj.toInt, min.toInt, fix.toInt, Option(rest).getOrElse("")) case _ => throw new IllegalArgumentException( s"Version must conform to regex given by string ${splitRegex.toString()}") } } match { case Success(version) => version case Failure(nfe: NumberFormatException) => throw VersionException(versionString, Some( new IllegalArgumentException("Version must start with X.Y.Z, " + "where X, Y and Z are non negative integers!", nfe))) case Failure(e) => throw VersionException(versionString, Some(e)) } } } case class VersionException(versionString: String, cause: Option[Throwable] = None) extends Exception(s"Could not parse version '$versionString'", cause.orNull)
Example 163
Source File: TransformBuilder.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.runtime.transformer.builder
import com.truecar.mleap.runtime.types.DataType
import com.truecar.mleap.runtime.Row
import scala.util.{Failure, Try}
trait TransformBuilder[T] extends Serializable {
def withInput(t: T, name: String): Try[(T, Int)]
def withInput(t: T, name: String, dataType: DataType): Try[(T, Int)]
def withOutput(t: T, name: String, dataType: DataType)
(o: (Row) => Any): Try[T]
def withSelect(t: T, fieldNames: Seq[String]): Try[T]
def withDrop(t: T, name: String): Try[T]
}
object TransformBuilder {
implicit class Ops[T: TransformBuilder](t: T) {
def withInput(name: String): Try[(T, Int)] = {
implicitly[TransformBuilder[T]].withInput(t, name)
}
def withInput(name: String, dataType: DataType): Try[(T, Int)] = {
implicitly[TransformBuilder[T]].withInput(t, name, dataType)
}
def withOutput(name: String, dataType: DataType)
(o: (Row) => Any): Try[T] = {
implicitly[TransformBuilder[T]].withOutput(t, name, dataType)(o)
}
def withSelect(fieldNames: Seq[String]): Try[T] = {
implicitly[TransformBuilder[T]].withSelect(t, fieldNames)
}
def withDrop(name: String): Try[T] = {
implicitly[TransformBuilder[T]].withDrop(t, name)
}
}
}
Example 164
Source File: PropertiesLoader.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.archaius import akka.actor.Actor import com.amazonaws.services.dynamodbv2.model.ScanRequest import com.netflix.atlas.json.Json import com.typesafe.config.Config import com.typesafe.scalalogging.StrictLogging import scala.util.Failure import scala.util.Success class PropertiesLoader(config: Config, propContext: PropertiesContext, dynamoService: DynamoService) extends Actor with StrictLogging { private val table = config.getString("netflix.iep.archaius.table") import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global context.system.scheduler.schedule(5.seconds, 5.seconds, self, PropertiesLoader.Tick) def receive: Receive = { case PropertiesLoader.Tick => val future = dynamoService.execute { client => val matches = List.newBuilder[PropertiesApi.Property] val request = new ScanRequest().withTableName(table) var response = client.scan(request) matches ++= process(response.getItems) while (response.getLastEvaluatedKey != null) { request.setExclusiveStartKey(response.getLastEvaluatedKey) response = client.scan(request) matches ++= process(response.getItems) } matches.result() } future.onComplete { case Success(vs) => propContext.update(vs) case Failure(t) => logger.error("failed to refresh properties from dynamodb", t) } } private def process(items: Items): PropList = { import scala.jdk.CollectionConverters._ items.asScala .filter(_.containsKey("data")) .map(_.get("data").getS) .map(s => Json.decode[PropertiesApi.Property](s)) .toList } } object PropertiesLoader { case object Tick }
Example 165
Source File: DataSourceValidator.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.stream import com.netflix.atlas.eval.stream.Evaluator.DataSource import com.netflix.atlas.eval.stream.Evaluator.DataSources import com.netflix.atlas.json.Json import scala.collection.mutable import scala.jdk.CollectionConverters._ import scala.util.Failure import scala.util.Success import scala.util.Try // Parse and validation DataSource's case class DataSourceValidator(maxDataSourcesPerSession: Int, validateFunc: DataSource => Unit) { def validate(input: String): Either[List[IdAndError], DataSources] = { val errorMap = mutable.Map[String, mutable.Set[String]]() var dataSourceList: List[DataSource] = List.empty[DataSource] try { dataSourceList = Json.decode[List[DataSource]](input) } catch { case e: Exception => addError("_", s"failed to parse input: ${e.getMessage}", errorMap) } validate(dataSourceList, errorMap) } def validate(dataSourceList: List[DataSource]): Either[List[IdAndError], DataSources] = { validate(dataSourceList, mutable.Map.empty) } private def validate( dataSourceList: List[DataSource], errorMap: mutable.Map[String, mutable.Set[String]] ): Either[List[IdAndError], DataSources] = { // Validate size limit first if (dataSourceList.size > maxDataSourcesPerSession) { addError("_", s"number of DataSources cannot exceed $maxDataSourcesPerSession", errorMap) } else { // Validate each DataSource val visitedIds = mutable.Set[String]() dataSourceList.foreach(ds => { val id = ds.getId // Validate id if (id == null) { addError(id, "id cannot be null", errorMap) } else if (id.isEmpty) { addError(id, "id cannot be empty", errorMap) } else { if (visitedIds.contains(id)) { addError(id, "id cannot be duplicated", errorMap) } else { visitedIds.add(id) } } // Validate uri Try(validateFunc(ds)) match { case Success(_) => case Failure(e) => addError(id, s"invalid uri: ${e.getMessage}", errorMap) } }) } if (errorMap.nonEmpty) { Left( errorMap .map { case (id, errorList) => IdAndError(id, errorList.mkString("; ")) } .toList .sortBy(_.id) ) } else { Right(new DataSources(dataSourceList.toSet.asJava)) } } private def addError( id: String, value: String, errorMap: mutable.Map[String, mutable.Set[String]] ): Unit = { val normalizedId = if (id == null) { "<null_id>" } else if (id.isEmpty) { "<empty_id>" } else { id } errorMap.getOrElseUpdate(normalizedId, mutable.Set[String]()) += value } case class IdAndError(id: String, error: String) }
Example 166
Source File: TypesafeConfigSource.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config.typesafe import java.io.File import java.lang.{ Boolean => JBoolean } import com.typesafe.config._ import zio.config.PropertyTree.{ Leaf, _ } import zio.config.{ ConfigSource, _ } import zio.{ IO, Task, ZIO } import scala.collection.JavaConverters._ import scala.util.{ Failure, Success, Try } object TypesafeConfigSource { def fromDefaultLoader: Either[String, ConfigSource] = fromTypesafeConfig(ConfigFactory.load.resolve) def fromHoconFile[A]( file: File ): Task[ConfigSource] = IO.effect(ConfigFactory.parseFile(file).resolve) .flatMap(typesafeConfig => { ZIO .fromEither(fromTypesafeConfig(typesafeConfig)) .mapError(str => new RuntimeException(str)) }) def fromHoconString( input: String ): Either[String, zio.config.ConfigSource] = fromTypesafeConfig( ConfigFactory.parseString(input).resolve ) def fromTypesafeConfig( input: => com.typesafe.config.Config ): Either[String, ConfigSource] = Try { input } match { case Failure(exception) => Left(exception.getMessage) case Success(value) => getPropertyTree(value) match { case Left(value) => Left(value) case Right(value) => Right(ConfigSource.fromPropertyTree(value, "hocon", LeafForSequence.Invalid)) } } private[config] def getPropertyTree( input: com.typesafe.config.Config ): Either[String, PropertyTree[String, String]] = { def loopBoolean(value: Boolean) = Leaf(value.toString) def loopNumber(value: Number) = Leaf(value.toString) val loopNull = PropertyTree.empty def loopString(value: String) = Leaf(value) def loopList(values: List[ConfigValue]) = Sequence(values.map(loopAny)) def loopConfig(config: ConfigObject) = Record(config.asScala.toVector.map { case (key, value) => key -> loopAny(value) }.toMap) def loopAny(value: ConfigValue): PropertyTree[String, String] = value.valueType() match { case ConfigValueType.OBJECT => loopConfig(value.asInstanceOf[ConfigObject]) case ConfigValueType.LIST => loopList(value.asInstanceOf[ConfigList].asScala.toList) case ConfigValueType.BOOLEAN => loopBoolean(value.unwrapped().asInstanceOf[JBoolean]) case ConfigValueType.NUMBER => loopNumber(value.unwrapped().asInstanceOf[Number]) case ConfigValueType.NULL => loopNull case ConfigValueType.STRING => loopString(value.unwrapped().asInstanceOf[String]) } Try(loopConfig(input.root())) match { case Failure(t) => Left( "Unable to form the zio.config.PropertyTree from Hocon string." + " This may be due to the presence of explicit usage of nulls in hocon string. " + t.getMessage ) case Success(value) => Right(value) } } }
Example 167
Source File: TwitterSinkTask.scala From kafka-tweet-producer with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.clients.consumer.OffsetAndMetadata import org.apache.kafka.common.TopicPartition import org.apache.kafka.connect.sink.{SinkRecord, SinkTask} import scala.collection.JavaConverters._ import scala.util.{Success, Failure} class TwitterSinkTask extends SinkTask with Logging { var writer: Option[SimpleTwitterWriter] = None override def start(props: util.Map[String, String]): Unit = { val sinkConfig = new TwitterSinkConfig(props) writer = Some(new TwitterWriter( sinkConfig.getString(TwitterSinkConfig.CONSUMER_KEY_CONFIG), sinkConfig.getPassword(TwitterSinkConfig.CONSUMER_SECRET_CONFIG).value, sinkConfig.getString(TwitterSinkConfig.TOKEN_CONFIG), sinkConfig.getPassword(TwitterSinkConfig.SECRET_CONFIG).value)) } override def put(records: util.Collection[SinkRecord]): Unit = records.asScala .map(_.value.toString) .map(text => (text, writer match { case Some(writer) => writer.updateStatus(text) case None => Failure(new IllegalStateException("twitter writer is not set")) })) .foreach { case (text, result) => result match { case Success(id) => log.info(s"successfully tweeted `${text}`; got assigned id ${id}") case Failure(err) => log.warn(s"tweeting `${text}` failed: ${err.getMessage}") } } override def stop(): Unit = { } override def flush(map: util.Map[TopicPartition, OffsetAndMetadata]) = { } override def version(): String = "" }
Example 168
Source File: TwitterSourceConnector.scala From kafka-tweet-producer with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.connect.connector.{Task, Connector} import org.apache.kafka.connect.errors.ConnectException import scala.collection.JavaConverters._ import scala.util.{Failure, Try} override def start(props: util.Map[String, String]): Unit = { log.info(s"Starting Twitter source task with ${props.toString}.") configProps = props Try(new TwitterSourceConfig(props)) match { case Failure(f) => throw new ConnectException("Couldn't start Twitter source due to configuration error: " + f.getMessage, f) case _ => } } override def stop() = {} override def version(): String = "" }
Example 169
Source File: TwitterSinkConnector.scala From kafka-tweet-producer with Apache License 2.0 | 5 votes |
package com.eneco.trading.kafka.connect.twitter import java.util import org.apache.kafka.connect.connector.Task import org.apache.kafka.connect.errors.ConnectException import org.apache.kafka.connect.sink.SinkConnector import scala.collection.JavaConverters._ import scala.util.{Failure, Try} class TwitterSinkConnector extends SinkConnector with Logging { private var configProps : util.Map[String, String] = null override def start(props: util.Map[String, String]): Unit = { log.info(s"Starting Twitter sink task with ${props.toString}.") configProps = props Try(new TwitterSinkConfig(props)) match { case Failure(f) => throw new ConnectException("Couldn't start TwitterSinkConnector due to configuration error.", f) case _ => } } override def stop(): Unit = {} override def version(): String = "" }
Example 170
Source File: KafkaPayloadAvroSpecificCodec.scala From kafka-scala-api with Apache License 2.0 | 5 votes |
package com.example.avro import com.twitter.bijection.Injection import com.twitter.bijection.avro.SpecificAvroCodecs import org.apache.avro.specific.SpecificRecordBase import org.apache.log4j.Logger import scala.reflect.ClassTag import scala.util.{Failure, Success} class KafkaPayloadAvroSpecificCodec[A <: SpecificRecordBase : ClassTag] extends Serializable { @transient lazy private val logger = Logger.getLogger(getClass) @transient lazy implicit private val avroSpecificInjection = SpecificAvroCodecs.toBinary[A] def decodeValue(payload: KafkaPayload): Option[A] = { val decodedTry = Injection.invert[A, Array[Byte]](payload.value) decodedTry match { case Success(record) => Some(record) case Failure(ex) => logger.warn("Could not decode payload", ex) None } } def encodeValue(value: A): KafkaPayload = { val encoded = Injection[A, Array[Byte]](value) KafkaPayload(None, encoded) } } object KafkaPayloadAvroSpecificCodec { def apply[A <: SpecificRecordBase : ClassTag](): KafkaPayloadAvroSpecificCodec[A] = new KafkaPayloadAvroSpecificCodec[A] }
Example 171
Source File: ManifestUploader.scala From teamcity-s3-plugin with Apache License 2.0 | 5 votes |
package com.gu.teamcity import java.io.ByteArrayInputStream import java.util.Date import jetbrains.buildServer.messages.{BuildMessage1, DefaultMessagesInfo, Status} import jetbrains.buildServer.serverSide.{BuildServerAdapter, SRunningBuild} import org.joda.time.{DateTime, DateTimeZone} import org.json4s.JsonAST.JObject import org.json4s.JsonDSL._ import org.json4s.native.JsonMethods._ import scala.util.{Failure, Success} class ManifestUploader(config: S3ConfigManager, s3: S3) extends BuildServerAdapter { override def beforeBuildFinish(runningBuild: SRunningBuild) { import scala.collection.convert.wrapAsScala._ if (!runningBuild.isHasInternalArtifactsOnly) { val properties = Seq( "projectName" -> S3Plugin.cleanFullName(runningBuild), "buildNumber" -> runningBuild.getBuildNumber, "startTime" -> new DateTime(runningBuild.getStartDate).withZone(DateTimeZone.UTC).toString //Joda default is ISO8601 ) ++ runningBuild.getRevisions.flatMap(revision => Seq( "revision" -> revision.getRevision, "vcsURL" -> revision.getRoot.getProperties.get("url") )) ++ Option(runningBuild.getBranch).map(b => "branch" -> b.getDisplayName ).orElse(runningBuild.getVcsRootEntries.headOption.map(r => "branch" -> r.getProperties.get("branch") )) val propertiesJSON = pretty(render(properties.foldLeft(JObject())(_ ~ _))) val jsBytes = propertiesJSON.getBytes("UTF-8") config.buildManifestBucket.map { bucket => s3.upload(bucket, runningBuild, "build.json", new ByteArrayInputStream(jsBytes), jsBytes.length) match { case Failure(e) => runningBuild.getBuildLog().message(s"Error uploading manifest: ${e.getMessage}", Status.ERROR,new Date,DefaultMessagesInfo.MSG_BUILD_FAILURE,DefaultMessagesInfo.SOURCE_ID,null) case Success(_) => runningBuild.getBuildLog().message("Manifest S3 upload complete", Status.NORMAL,new Date,DefaultMessagesInfo.MSG_TEXT,DefaultMessagesInfo.SOURCE_ID,null) } } } } private def normalMessage(text: String) = new BuildMessage1(DefaultMessagesInfo.SOURCE_ID, DefaultMessagesInfo.MSG_TEXT, Status.NORMAL, new Date, text) }
Example 172
Source File: MusicManager.scala From AckCord with MIT License | 5 votes |
package ackcord import scala.concurrent.duration.FiniteDuration import scala.util.{Failure, Success} import ackcord.data.{GuildId, VoiceGuildChannelId} import ackcord.lavaplayer.LavaplayerHandler import akka.actor.typed._ import akka.actor.typed.scaladsl.AskPattern._ import akka.actor.typed.scaladsl._ import akka.util.Timeout import com.sedmelluq.discord.lavaplayer.player.AudioPlayer object MusicManager { private[ackcord] def apply( cache: Cache, players: Map[GuildId, (AudioPlayer, ActorRef[LavaplayerHandler.Command])] = Map.empty ): Behavior[Command] = Behaviors.receive { case (ctx, ConnectToChannel(guildId, channelId, force, createPlayer, timeoutDur, replyTo)) => implicit val timeout: Timeout = Timeout(timeoutDur) implicit val system: ActorSystem[Nothing] = ctx.system import ctx.executionContext val (usedPlayer, actor) = players.getOrElse( guildId, { val player = createPlayer() (player, ctx.spawn(LavaplayerHandler(player, guildId, cache), guildId.asString)) } ) //TODO: Handle errors actor.ask[LavaplayerHandler.Reply](LavaplayerHandler.ConnectVoiceChannel(channelId, force, _)).onComplete { case Success(_) => replyTo ! GotPlayer(usedPlayer) case Failure(e) => replyTo ! GotError(e) } apply(cache, players.updated(guildId, (usedPlayer, actor))) case (_, DisconnectFromChannel(guildId, destroyPlayer)) => players.get(guildId).foreach { case (player, actor) => actor ! LavaplayerHandler.DisconnectVoiceChannel if (destroyPlayer) { player.destroy() } } apply(cache, players - guildId) case (_, SetChannelPlaying(guildId, playing)) => players.get(guildId).foreach { case (_, actor) => actor ! LavaplayerHandler.SetPlaying(playing) } Behaviors.same } sealed trait Command sealed trait ConnectToChannelResponse case class GotPlayer(player: AudioPlayer) extends ConnectToChannelResponse case class GotError(e: Throwable) extends ConnectToChannelResponse private[ackcord] case class ConnectToChannel( guildId: GuildId, channelId: VoiceGuildChannelId, force: Boolean, createPlayer: () => AudioPlayer, timeout: FiniteDuration, replyTo: ActorRef[ConnectToChannelResponse] ) extends Command private[ackcord] case class DisconnectFromChannel(guildId: GuildId, destroyPlayer: Boolean) extends Command private[ackcord] case class SetChannelPlaying(guildId: GuildId, playing: Boolean) extends Command }
Example 173
Source File: VoiceUDPHandler.scala From AckCord with MIT License | 5 votes |
package ackcord.voice import java.net.InetSocketAddress import scala.concurrent.duration._ import scala.util.{Failure, Success} import ackcord.data.{RawSnowflake, UserId} import akka.NotUsed import akka.actor.typed._ import akka.actor.typed.scaladsl._ import akka.stream.OverflowStrategy import akka.stream.scaladsl.{Keep, Sink, Source, SourceQueueWithComplete} import akka.util.ByteString import org.slf4j.Logger object VoiceUDPHandler { def apply( address: String, port: Int, ssrc: Int, serverId: RawSnowflake, userId: UserId, soundProducer: Source[ByteString, NotUsed], soundConsumer: Sink[AudioAPIMessage, NotUsed], parent: ActorRef[VoiceHandler.Command] ): Behavior[Command] = Behaviors .supervise( Behaviors.setup[Command] { ctx => implicit val system: ActorSystem[Nothing] = ctx.system val ((queue, futIp), watchDone) = soundProducer .viaMat( VoiceUDPFlow .flow( new InetSocketAddress(address, port), ssrc, serverId, userId, Source.queue[Option[ByteString]](0, OverflowStrategy.dropBuffer) ) .watchTermination()(Keep.both) )(Keep.right) .to(soundConsumer) .run() ctx.pipeToSelf(futIp) { case Success(value) => IPDiscoveryResult(value) case Failure(e) => SendExeption(e) } ctx.pipeToSelf(watchDone)(_ => ConnectionDied) handle(ctx, ctx.log, ssrc, queue, parent) } ) .onFailure( SupervisorStrategy .restartWithBackoff(100.millis, 5.seconds, 1D) .withResetBackoffAfter(10.seconds) .withMaxRestarts(5) ) def handle( ctx: ActorContext[Command], log: Logger, ssrc: Int, queue: SourceQueueWithComplete[Option[ByteString]], parent: ActorRef[VoiceHandler.Command] ): Behavior[Command] = Behaviors.receiveMessage { case SendExeption(e) => throw e case ConnectionDied => Behaviors.stopped case Shutdown => queue.complete() Behaviors.same case IPDiscoveryResult(VoiceUDPFlow.FoundIP(localAddress, localPort)) => parent ! VoiceHandler.GotLocalIP(localAddress, localPort) Behaviors.same case SetSecretKey(key) => queue.offer(key) Behaviors.same } sealed trait Command case object Shutdown extends Command private case class SendExeption(e: Throwable) extends Command private case object ConnectionDied extends Command private case class IPDiscoveryResult(foundIP: VoiceUDPFlow.FoundIP) extends Command private[voice] case class SetSecretKey(key: Option[ByteString]) extends Command }
Example 174
Source File: EmbeddedKafkaSpecSupport.scala From embedded-kafka-schema-registry with MIT License | 5 votes |
package net.manub.embeddedkafka.schemaregistry import java.net.{InetAddress, Socket} import net.manub.embeddedkafka.schemaregistry.EmbeddedKafkaSpecSupport.{ Available, NotAvailable, ServerStatus } import org.scalatest.Assertion import org.scalatest.concurrent.{Eventually, IntegrationPatience} import org.scalatest.matchers.should.Matchers import org.scalatest.time.{Milliseconds, Seconds, Span} import org.scalatest.wordspec.AnyWordSpecLike import scala.util.{Failure, Success, Try} trait EmbeddedKafkaSpecSupport extends AnyWordSpecLike with Matchers with Eventually with IntegrationPatience { implicit val config: PatienceConfig = PatienceConfig(Span(1, Seconds), Span(100, Milliseconds)) def expectedServerStatus(port: Int, expectedStatus: ServerStatus): Assertion = eventually { status(port) shouldBe expectedStatus } private def status(port: Int): ServerStatus = { Try(new Socket(InetAddress.getByName("localhost"), port)) match { case Failure(_) => NotAvailable case Success(_) => Available } } } object EmbeddedKafkaSpecSupport { sealed trait ServerStatus case object Available extends ServerStatus case object NotAvailable extends ServerStatus }
Example 175
Source File: LeapFrameBuilder.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.runtime.transformer.builder import com.truecar.mleap.runtime.{Row, LeapFrame} import com.truecar.mleap.runtime.types.{DataType, StructField} import scala.util.{Failure, Success, Try} case class LeapFrameBuilder[T: LeapFrame](frame: T) extends Serializable object LeapFrameBuilder { implicit def LeapFrameBuilderTransformBuilder[T: LeapFrame]: TransformBuilder[LeapFrameBuilder[T]] = { new TransformBuilder[LeapFrameBuilder[T]] { override def withInput(t: LeapFrameBuilder[T], name: String): Try[(LeapFrameBuilder[T], Int)] = { LeapFrame.schema(t.frame).tryIndexOf(name).map((t, _)) } override def withInput(t: LeapFrameBuilder[T], name: String, dataType: DataType): Try[(LeapFrameBuilder[T], Int)] = { val schema = LeapFrame.schema(t.frame) schema.getField(name) match { case Some(field) => if(field.dataType == dataType) { Success(t, schema.indexOf(name)) } else { Failure(new Error(s"Field $name expected data type ${field.dataType} but found $dataType")) } case None => Failure(new Error(s"Field $name does not exist")) } } override def withOutput(t: LeapFrameBuilder[T], name: String, dataType: DataType)(o: (Row) => Any): Try[LeapFrameBuilder[T]] = { LeapFrame.withField(t.frame, StructField(name, dataType), o).map { frame2 => t.copy(frame = frame2) } } override def withSelect(t: LeapFrameBuilder[T], fieldNames: Seq[String]): Try[LeapFrameBuilder[T]] = { LeapFrame.select(t.frame, fieldNames: _*).map(frame => LeapFrameBuilder(frame)) } override def withDrop(t: LeapFrameBuilder[T], name: String): Try[LeapFrameBuilder[T]] = { LeapFrame.dropField(t.frame, name).map(frame => LeapFrameBuilder(frame)) } } } }
Example 176
Source File: StructType.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.runtime.types import scala.util.{Failure, Success, Try} def dropIndex(index: Int): StructType = { StructType(fields.take(index) ++ fields.drop(index + 1)) } def tryIndexOf(name: String): Try[Int] = { if(contains(name)) { Success(indexOf(name)) } else { Failure(new Error(s"Field $name does not exist")) } } }
Example 177
Source File: IterateeMain.scala From advanced-scala-code with Apache License 2.0 | 5 votes |
package iteratee import scala.util.{Failure, Success} object IterateeMain { def fileExample(): Unit = { import io.iteratee.monix.task._ import java.io.File val wordsE = readLines(new File("license.txt")).flatMap { line => enumIndexedSeq(line.split("\\W")) } val noEmptyLinesEE = filter[String](str => str.trim.length > 0) val toLowerEE = map[String, String](_.toLowerCase) val countWordsI = fold[String, Map[String, Int]](Map.empty) { (acc, next) => acc.get(next) match { case None => acc + (next -> 1) case Some(num) => acc + (next -> (1 + num)) } } val dataT = wordsE.through(noEmptyLinesEE). through(toLowerEE).into(countWordsI).map { dataMap => dataMap.toList.sortWith( _._2 > _._2).take(5).map(_._1) } import monix.execution.Scheduler.Implicits.global dataT.runOnComplete { case Success(data) => println(data) case Failure(th) => th.printStackTrace() } } def main(args: Array[String]) { import io.iteratee.modules.id._ // Just one Int val singleNumE = enumOne(42) val singleNumI = takeI[Int](1) val singleNumResult = singleNumE.into(singleNumI) println(singleNumResult) // Incrementing one Int val incrementNumEE = map[Int, Int](_ + 1) val incrementedNumResult = singleNumE.through(incrementNumEE).into(singleNumI) println(incrementedNumResult) // First 10 even numbers val naturalsE = iterate(1)(_ + 1) val moreThan100EE = filter[Int](_ >= 100) val evenFilterEE = filter[Int](_ % 2 == 0) val first10I = takeI[Int](10) println(naturalsE.through(moreThan100EE).through(evenFilterEE).into(first10I)) { import io.iteratee.modules.eval._ // Summing N first numbers val naturalsE = iterate(1)(_ + 1) val limit1kEE = take[Int](30000) val sumI = fold[Int, Int](0) { (acc, next) => acc + next } println(naturalsE.through(limit1kEE).into(sumI).value) } fileExample() } }
Example 178
Source File: package.scala From theGardener with Apache License 2.0 | 5 votes |
import java.io.File import play.api.Logging import scala.concurrent._ import scala.util.control.NonFatal import scala.util.{Failure, Try} package object utils extends Logging { implicit class TryOps[T](t: Try[T]) { def logError(msg: => String): Try[T] = t.recoverWith { case e => logger.error(msg, e) Failure(e) } } implicit class FutureOps[T](f: Future[T]) { def logError(msg: => String)(implicit ec: ExecutionContext): Future[T] = f.recoverWith { case NonFatal(e) => logger.error(msg, e) Future.failed(e) } } implicit class PathExt(path: String) { def fixPathSeparator: String = path.replace('/', File.separatorChar) } }
Example 179
Source File: TgzTransformerSpec.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser import java.io._ import java.nio.file.{Files, Path} import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveInputStream} import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.apache.commons.io.FileUtils import org.scalatest._ import scala.collection.mutable.ListBuffer import scala.util.{Failure, Success} class TgzTransformerSpec extends WordSpec with Matchers with BeforeAndAfterEach with OptionValues with TryValues{ val tgzPath = new File(this.getClass.getResource("/help-frontend/uk/gov/hmrc/help-frontend_2.11/1.26.0-3-gd7ed03c/help-frontend_2.11-1.26.0-3-gd7ed03c.tgz").toURI).toPath var transformer:TgzTransformer = _ val candidate_1_26_0_3_gd7ed03c = ReleaseCandidateVersion("1.26.0-3-gd7ed03c") val release_1_4_0 = ReleaseVersion("1.4.0") var tmpDir:Path = _ override def beforeEach(){ tmpDir = Files.createTempDirectory("tmp") transformer = new TgzTransformer() FileUtils.copyFileToDirectory(tgzPath.toFile, tmpDir.toFile) } override def afterEach(){ FileUtils.deleteDirectory(tmpDir.toFile) } "the transformer" should { "decompress the tgz, rename the main folder and compress it back" in { val inFile = new File(tmpDir.toFile, tgzPath.getFileName.toString).toPath val targetFilePath = tmpDir.resolve("help-frontend-1.4.0.tgz") val originalTarEntries = listTgzEntries(inFile) assertTarEntry(originalTarEntries, "./help-frontend-1.26.0-3-gd7ed03c/") assertTarEntry(originalTarEntries, "./help-frontend-1.4.0/", exists = false) assertTarEntry(originalTarEntries, "./start-docker.sh", mode = Some(493)) val outFileTry = transformer(inFile, "help-frontend", candidate_1_26_0_3_gd7ed03c, release_1_4_0, targetFilePath) outFileTry match { case Success(outFile) => val tarEntries = listTgzEntries(targetFilePath) assertTarEntry(tarEntries, "./help-frontend-1.26.0-3-gd7ed03c/", exists = false) assertTarEntry(tarEntries, "./help-frontend-1.4.0/") assertTarEntry(tarEntries, "./start-docker.sh", mode = Some(493)) case Failure(e) => fail("Caught exception: " + e.getMessage, e) } } } private def listTgzEntries(localTgzFile: Path) : List[TarArchiveEntry] = { val bytes = new Array[Byte](2048) val fin = new BufferedInputStream(new FileInputStream(localTgzFile.toFile)) val gzIn = new GzipCompressorInputStream(fin) val tarIn = new TarArchiveInputStream(gzIn) val entries = ListBuffer[TarArchiveEntry]() Iterator continually tarIn.getNextTarEntry takeWhile (null !=) foreach { tarEntry => entries += tarEntry } tarIn.close() entries.toList } private def assertTarEntry(tarEntries: List[TarArchiveEntry], entryName: String, exists: Boolean = true, mode: Option[Int] = None) = { val entryOption = tarEntries.find(_.getName == entryName) entryOption match { case Some(entry) => exists shouldBe true mode.foreach { m => m shouldBe entry.getMode} case None => exists shouldBe false } } }
Example 180
Source File: FakeBintrayRepoConnector.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser.bintray import java.nio.file.{Path, Paths} import scala.collection.mutable import scala.util.{Failure, Success, Try} class FakeBintrayRepoConnector(filesuffix:String = "", jarResource:Option[String], bintrayFiles:Set[String], targetExists:Boolean = false) extends BintrayRepoConnector { val downloadedFiles = mutable.Set[String]() val uploadedFiles = mutable.Set[(VersionDescriptor, Path, String)]() var lastPublishDescriptor: Option[VersionDescriptor] = None override def findJar(jarFileName: String, jarUrl: String, version: VersionDescriptor): Option[Path] = jarResource.map { x => Paths.get(this.getClass.getResource(filesuffix + x).toURI) } override def publish(version: VersionDescriptor): Try[Unit] = { lastPublishDescriptor = Some(version) Success(Unit) } override def findFiles(version: VersionDescriptor): Try[List[String]] = Success(bintrayFiles.toList ++ jarResource) override def downloadFile(url: String, fileName: String): Try[Path] = { downloadedFiles.add(url) val success = Success { val s = filesuffix + fileName val resource = this.getClass.getResource(s) val i = resource.toURI val path = Paths.get(i) path } success } override def uploadFile(version: VersionDescriptor, filePath: Path, url: String): Try[Unit] = { uploadedFiles.add((version, filePath, url)) Success(Unit) } override def verifyTargetDoesNotExist(version: VersionDescriptor): Try[Unit] = targetExists match { case true => Failure(new IllegalArgumentException("Failed in test")) case false => Success(Unit) } override def getRepoMetaData(repoName: String, artefactName: String): Try[Unit] = Success(Unit) }
Example 181
Source File: ArtefactMetaDataProviderSpecs.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser import java.nio.file.Paths import org.scalatest.{Matchers, TryValues, WordSpec} import uk.gov.hmrc.releaser.github.GithubConnector import scala.util.Failure class ArtefactMetaDataProviderSpecs extends WordSpec with Matchers with TryValues { "ArtefactMetaData" should { "build instance from file" in { val md = new ArtefactMetaDataProvider().fromJarFile(Paths.get(this.getClass.getResource("/sbt-bobby/uk.gov.hmrc/sbt-bobby/scala_2.10/sbt_0.13/0.8.1-4-ge733d26/jars/sbt-bobby.jar").toURI)) match { case Failure(e) => fail(e) case s => s } md.success.value.commitAuthor shouldBe "Charles Kubicek" md.success.value.sha shouldBe "e733d26fa504c040f2c95ecd25a3a55399a00883" md.success.value.commitDate shouldBe GithubConnector.githubDateTimeFormatter.parseDateTime("2015-04-09T10:18:12.000Z") } } }
Example 182
Source File: Releaser.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser import java.io.File import java.nio.file.{Files, Path} import org.apache.commons.io.FileUtils import uk.gov.hmrc.releaser.bintray.{BintrayHttp, BintrayRepoConnector, DefaultBintrayRepoConnector} import uk.gov.hmrc.releaser.github.{GithubConnector, Repo} import uk.gov.hmrc.{CredentialsFinder, FileDownloader, Logger} import scala.util.{Failure, Success, Try} object ReleaserMain { def main(args: Array[String]): Unit = { val result = Releaser(args) System.exit(result) } } object Releaser extends Logger { import ArgParser._ def apply(args: Array[String]): Int = { parser.parse(args, Config()) match { case Some(config) => val githubName = config.githubNameOverride.getOrElse(config.artefactName) run(config.artefactName, ReleaseCandidateVersion(config.rcVersion), config.releaseType, githubName, config.releaseNotes, config.dryRun) case None => -1 } } def run(artefactName: String, rcVersion: ReleaseCandidateVersion, releaseType: ReleaseType.Value, gitHubName: String, releaseNotes: Option[String], dryRun: Boolean = false): Int = { val githubCredsFile = System.getProperty("user.home") + "/.github/.credentials" val bintrayCredsFile = System.getProperty("user.home") + "/.bintray/.credentials" val githubCredsOpt = CredentialsFinder.findGithubCredsInFile(new File(githubCredsFile).toPath) val bintrayCredsOpt = CredentialsFinder.findBintrayCredsInFile(new File(bintrayCredsFile).toPath) doReleaseWithCleanup { directories => if (githubCredsOpt.isEmpty) { log.info(s"Didn't find github credentials in $githubCredsFile") -1 } else if (bintrayCredsOpt.isEmpty) { log.info(s"Didn't find Bintray credentials in $bintrayCredsFile") -1 } else { val releaserVersion = getClass.getPackage.getImplementationVersion val metaDataProvider = new ArtefactMetaDataProvider() val gitHubDetails = if (dryRun) GithubConnector.dryRun(githubCredsOpt.get, releaserVersion) else GithubConnector(githubCredsOpt.get, releaserVersion) val bintrayDetails = if (dryRun) BintrayRepoConnector.dryRun(bintrayCredsOpt.get, directories.workDir) else BintrayRepoConnector(bintrayCredsOpt.get, directories.workDir) val bintrayRepoConnector = new DefaultBintrayRepoConnector(directories.workDir, new BintrayHttp(bintrayCredsOpt.get), new FileDownloader) val coordinator = new Coordinator(directories.stageDir, metaDataProvider, gitHubDetails, bintrayRepoConnector) val result = coordinator.start(artefactName, Repo(gitHubName), rcVersion, releaseType, releaseNotes) result match { case Success(targetVersion) => log.info(s"Releaser successfully released $artefactName $targetVersion") 0 case Failure(e) => e.printStackTrace() log.info(s"Releaser failed to release $artefactName $rcVersion with error '${e.getMessage}'") 1 } } } } def doReleaseWithCleanup[T](f: ReleaseDirectories => T): T = { val directories = ReleaseDirectories() try { f(directories) } finally { log.info("cleaning releaser work directory") directories.delete().recover{case t => log.warn(s"failed to delete releaser work directory ${t.getMessage}")} } } } case class ReleaseDirectories(tmpDirectory: Path = Files.createTempDirectory("releaser")) { lazy val workDir = Files.createDirectories(tmpDirectory.resolve("work")) lazy val stageDir = Files.createDirectories(tmpDirectory.resolve("stage")) def delete() = Try { FileUtils.forceDelete(tmpDirectory.toFile) } }
Example 183
Source File: MetaDataProvider.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser import java.nio.file.Path import java.util.jar.Manifest import java.util.zip.ZipFile import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import uk.gov.hmrc.releaser.github.CommitSha import scala.collection.JavaConversions._ import scala.io.Source import scala.util.{Failure, Success, Try} trait MetaDataProvider { def fromJarFile(p: Path): Try[ArtefactMetaData] def fromCommitManifest(p: Path): Try[ArtefactMetaData] } case class ArtefactMetaData(sha:CommitSha, commitAuthor:String, commitDate:DateTime) class ArtefactMetaDataProvider extends MetaDataProvider { import ArtefactMetaDataProvider._ def fromJarFile(p: Path): Try[ArtefactMetaData] = { Try {new ZipFile(p.toFile) }.flatMap { jarFile => jarFile.entries().filter(_.getName == "META-INF/MANIFEST.MF").toList.headOption.map { ze => val man = new Manifest(jarFile.getInputStream(ze)) ArtefactMetaData( man.getMainAttributes.getValue("Git-Head-Rev"), man.getMainAttributes.getValue("Git-Commit-Author"), gitCommitDateFormat.parseDateTime(man.getMainAttributes.getValue("Git-Commit-Date")) ) }.toTry(new Exception(s"Failed to retrieve manifest from $p")) } } def fromCommitManifest(p: Path): Try[ArtefactMetaData] = { Try { val map = Source.fromFile(p.toFile) .getLines().toSeq .map(_.split("=")) .map { case Array(key, value) => key.trim -> value.trim }.toMap ArtefactMetaData(map("sha"), map("author"), gitCommitDateFormat.parseDateTime(map("date"))) } } } object ArtefactMetaDataProvider { val gitCommitDateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ") implicit class OptionPimp[A](opt: Option[A]){ def toTry(e:Exception):Try[A] = opt match { case Some(x) => Success(x) case None => Failure(e) } } }
Example 184
Source File: DefaultBintrayRepoConnector.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser.bintray import java.net.{HttpURLConnection, URL} import java.nio.file.Path import play.api.libs.json.{JsValue, Json} import uk.gov.hmrc.{FileDownloader, Logger, ServiceCredentials} import scala.util.{Failure, Success, Try} object BintrayRepoConnector extends Logger { def apply(bintrayCreds: ServiceCredentials, workDir : Path): BintrayRepoConnector = new DefaultBintrayRepoConnector(workDir, new BintrayHttp(bintrayCreds), new FileDownloader()) def dryRun(bintrayCreds: ServiceCredentials, workDir : Path) = { log.info("Bintray : running in dry-run mode") val dryRunHttp = new BintrayHttp(bintrayCreds){ override def emptyPost(url:String): Try[Unit] = { println("BintrayHttp emptyPost DRY_RUN");Success(Unit)} override def putFile(version: VersionDescriptor, file: Path, url: String): Try[Unit] = { println("BintrayHttp putFile DRY_RUN");Success(Unit) } } new DefaultBintrayRepoConnector(workDir, dryRunHttp, new FileDownloader()) } } trait BintrayRepoConnector { def findJar(jarFileName: String, jarUrl: String, version: VersionDescriptor): Option[Path] def publish(version: VersionDescriptor): Try[Unit] def downloadFile(url: String, fileName: String): Try[Path] def uploadFile(version: VersionDescriptor, filePath: Path, url: String): Try[Unit] def verifyTargetDoesNotExist(version: VersionDescriptor): Try[Unit] def findFiles(version: VersionDescriptor): Try[List[String]] def getRepoMetaData(repoName:String, artefactName: String): Try[Unit] } class DefaultBintrayRepoConnector(workDir: Path, bintrayHttp: BintrayHttp, fileDownloader: FileDownloader) extends BintrayRepoConnector with Logger { def publish(version: VersionDescriptor):Try[Unit] = { val url = BintrayPaths.publishUrlFor(version) bintrayHttp.emptyPost(url) } def verifyTargetDoesNotExist(version: VersionDescriptor): Try[Unit] = { val url = BintrayPaths.fileListUrlFor(version) log.info(s"Bintray : checking to see if $url exists") val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod("HEAD") conn.connect() conn.getResponseCode match { case 200 => Failure(new IllegalArgumentException(s"${version.artefactName} ${version.version} already exists")) case _ => Success() } } def findJar(jarFileName: String, jarUrl: String, version: VersionDescriptor): Option[Path] = { downloadFile(jarUrl, jarFileName) match { case Success(x) => Some(x) case Failure(y) => None } } def uploadFile(version: VersionDescriptor, filePath: Path, url: String): Try[Unit] = { bintrayHttp.putFile(version, filePath, url) } def downloadFile(url: String, fileName: String): Try[Path] = { val targetFile = workDir.resolve(fileName) fileDownloader.url2File(url, targetFile) map { unit => targetFile } } def findFiles(version: VersionDescriptor): Try[List[String]] = { val url = BintrayPaths.fileListUrlFor(version) bintrayHttp.get(url).map { st => val fileNames: Seq[JsValue] = Json.parse(st) \\ "path" fileNames.map(_.as[String]).toList } } def getRepoMetaData(repoName:String, artefactName: String): Try[Unit] = { val url = BintrayPaths.metadata(repoName, artefactName) bintrayHttp.get(url).map { _ => Unit} } }
Example 185
Source File: Utils.scala From scala-clippy with Apache License 2.0 | 5 votes |
package com.softwaremill.clippy import java.io.{ByteArrayOutputStream, InputStream} import java.io.Closeable import scala.util.control.NonFatal import scala.util.{Failure, Try} object Utils { def runNonDaemon(t: => Unit) = { val shutdownHook = new Thread() { private val lock = new Object @volatile private var didRun = false override def run() = lock.synchronized { if (!didRun) { t didRun = true } } } Runtime.getRuntime.addShutdownHook(shutdownHook) try shutdownHook.run() finally Runtime.getRuntime.removeShutdownHook(shutdownHook) } def inputStreamToBytes(is: InputStream): Array[Byte] = try { val baos = new ByteArrayOutputStream() val buf = new Array[Byte](512) var read = 0 while ({ read = is.read(buf, 0, buf.length); read } != -1) { baos.write(buf, 0, read) } baos.toByteArray } finally is.close() object TryWith { def apply[C <: Closeable, R](resource: => C)(f: C => R): Try[R] = Try(resource).flatMap(resourceInstance => { try { val returnValue = f(resourceInstance) Try(resourceInstance.close()).map(_ => returnValue) } catch { case NonFatal(exceptionInFunction) => try { resourceInstance.close() Failure(exceptionInFunction) } catch { case NonFatal(exceptionInClose) => exceptionInFunction.addSuppressed(exceptionInClose) Failure(exceptionInFunction) } } }) } }
Example 186
Source File: OpticsExamplesUnitTest.scala From scala-tutorials with MIT License | 5 votes |
package com.baeldung.scala.monocle
import org.scalatest._
import org.scalatest.Assertions._
import scala.util.{Success, Failure}
import OpticsExamples._
class OpticsExamplesUnitTest extends FlatSpec with Matchers {
"OpticExamples" should "update stock without Lenses" in {
val currentStock = 10
val item = Item("123sku", 35L, currentStock, NoDiscount())
val cart = Cart("abc123", item, 1)
val user = User("joe", cart)
val newUser = updateStockWithoutLenses(user)
assert(newUser.cart.item.leftInStock == currentStock - 1)
}
it should "update stock with Lenses" in {
val currentStock = 10
val item = Item("123sku", 35L, currentStock, NoDiscount())
val cart = Cart("abc123", item, 1)
val user = User("joe", cart)
val newUser = updateStockWithLenses(user)
assert(newUser.cart.item.leftInStock == currentStock - 1)
}
it should "update discount percentage values" in {
val originalDiscount = 10L
val newDiscount = 5L
val updatedCart = updateDiscountedItemsPrice(
Cart("abc", Item("item123", 23L, 1, PercentageOff(originalDiscount)), 1),
newDiscount
)
assert(updatedCart.item.discount == PercentageOff(newDiscount))
}
it should "not update discount fix price values" in {
val originalDiscount = 10L
val newDiscount = 5L
val updatedCart = updateDiscountedItemsPrice(
Cart("abc", Item("item123", 23L, 1, FixPriceOff(originalDiscount)), 1),
newDiscount
)
assert(updatedCart.item.discount == FixPriceOff(originalDiscount))
}
it should "return the Fix Off discount value" in {
val value = 3L
assert(getDiscountValue(FixPriceOff(value)) == Some(value))
}
it should "return no discount value" in {
assert(getDiscountValue(NoDiscount()) == None)
}
it should "transform GBP to EUR correctly" in {
val x =
tranformCurrency.modify(gbp => gbp.copy(gbp.value + 90L))(PriceEUR(1000L))
assert(x.value == 1100L)
}
}
Example 187
Source File: FutureAndPromise.scala From scala-tutorials with MIT License | 5 votes |
package com.baeldung.scala.concurrency import java.math.BigInteger import java.net.URL import java.security.MessageDigest import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration import scala.concurrent.{Await, ExecutionContext, Future, Promise} import scala.util.control.NonFatal import scala.util.{Failure, Success} object ScalaAndPromise { def sampleFuture(): Future[Int] = Future { println("Long running computation started.") val result = { Thread.sleep(5) 5 } println("Our computation, finally finished.") result } type Name = String type Email = String type Password = String type Avatar = URL case class User(name: Name, email: Email, password: Password, avatar: Avatar) def exist(email: Email): Future[Boolean] = Future { Thread.sleep(100) // Call to the database takes time true } def md5hash(str: String): String = new BigInteger(1, MessageDigest .getInstance("MD5") .digest(str.getBytes) ).toString(16) def avatar(email: Email): Future[Avatar] = Future { Thread.sleep(200) // Call to the database takes time new Avatar("http://avatar.example.com/user/23k520f23f4.png") } def createUser(name: Name, email: Email, password: Password): Future[User] = for { _ <- exist(email) avatar <- avatar(email) hashedPassword = md5hash(password) } yield User(name, email, hashedPassword, avatar) def runByPromise[T](block: => T)(implicit ec: ExecutionContext): Future[T] = { val p = Promise[T] ec.execute { () => try { p.success(block) } catch { case NonFatal(e) => p.failure(e) } } p.future } } object FutureAndPromiseApp extends App { import ScalaAndPromise._ // Access to the value of Future by passing callback to the onComplete val userFuture: Future[User] = createUser("John", "John@emaple.com", "secret") userFuture.onComplete { case Success(user) => println(s"User created: $user") case Failure(exception) => println(s"Creating user failed due to the exception: $exception") } // Access to the value of Future by applying the result function on the Future value val user: User = Await.result(userFuture, Duration.Inf) // Forcing the Future value to be complete val completedFuture: Future[User] = Await.ready(userFuture, Duration.Inf) completedFuture.value.get match { case Success(user) => println(s"User created: $user") case Failure(exception) => println(s"Creating user failed due to the exception: $exception") } }
Example 188
Source File: Examples.scala From scala-tutorials with MIT License | 5 votes |
package com.baeldung.scala.exceptionhandling
import scala.util.{Try, Success, Failure}
import scala.util.control.Exception._
object Examples {
import CalculatorExceptions._
def tryCatch(a: Int, b: Int): Int = {
try {
return Calculator.sum(a, b)
// println(s"${a} + ${b} = ${result}")
} catch {
case e: IntOverflowException => -1
case e: NegativeNumberException => -2
} finally {
// This block will always be invoked
println("Calculation done!")
}
}
def trySuccessFailure(a: Int, b: Int): Try[Int] = Try {
Calculator.sum(a, b)
}
def catchObjects(a: Int, b: Int): Try[Int] = allCatch.withTry {
Calculator.sum(a, b)
}
val myCustomCatcher = catching(classOf[NegativeNumberException])
def customCatchObjects(a: Int, b: Int): Try[Int] = myCustomCatcher.withTry {
Calculator.sum(a, b)
}
}
Example 189
Source File: YamlFile.scala From sope with Apache License 2.0 | 5 votes |
package com.sope.etl.yaml import com.fasterxml.jackson.databind.JsonMappingException import com.sope.etl.transform.exception.YamlDataTransformException import com.sope.etl.transform.model.Failed import com.sope.etl.utils.RedactUtil import com.sope.etl.yaml.YamlParserUtil._ import com.sope.utils.Logging import scala.util.{Failure, Success, Try} def deserialize: T = Try { val yamlStr = text logInfo(s"Parsing $getYamlFileName YAML file :-\n $redactedText") parseYAML(yamlStr, modelClass) } match { case Success(t) => logInfo(s"Successfully parsed $getYamlFileName YAML File"); t case Failure(e) => e match { case e: JsonMappingException => Option(e.getLocation) match { case Some(location) => val errorMessage = getParseErrorMessage(location.getLineNr, location.getColumnNr) logError(errorMessage + s"\n${e.getMessage}") case None => e.getCause match { case YamlDataTransformException(_, failures) => failures.foreach { case Failed(msg, line, index) => val errorMessage = getParseErrorMessage(line, index) logError(errorMessage + s"\n$msg") } case _ => } } throw e case _ => throw e } } }
Example 190
Source File: BigtableDoFnTest.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.bigtable import java.util.concurrent.ConcurrentLinkedQueue import com.google.cloud.bigtable.grpc.BigtableSession import com.google.common.cache.{Cache, CacheBuilder} import com.google.common.util.concurrent.{Futures, ListenableFuture} import com.spotify.scio.testing._ import com.spotify.scio.transforms.BaseAsyncLookupDoFn.CacheSupplier import scala.jdk.CollectionConverters._ import scala.util.{Failure, Success} class BigtableDoFnTest extends PipelineSpec { "BigtableDoFn" should "work" in { val fn = new TestBigtableDoFn val output = runWithData(1 to 10)(_.parDo(fn)) .map(kv => (kv.getKey, kv.getValue.get())) output should contain theSameElementsAs (1 to 10).map(x => (x, x.toString)) } it should "work with cache" in { val fn = new TestCachingBigtableDoFn val output = runWithData((1 to 10) ++ (6 to 15))(_.parDo(fn)) .map(kv => (kv.getKey, kv.getValue.get())) output should contain theSameElementsAs ((1 to 10) ++ (6 to 15)).map(x => (x, x.toString)) BigtableDoFnTest.queue.asScala.toSet should contain theSameElementsAs (1 to 15) BigtableDoFnTest.queue.size() should be <= 20 } it should "work with failures" in { val fn = new TestFailingBigtableDoFn val output = runWithData(1 to 10)(_.parDo(fn)).map { kv => val r = kv.getValue.asScala match { case Success(v) => v case Failure(e) => e.getMessage } (kv.getKey, r) } output should contain theSameElementsAs (1 to 10).map { x => val prefix = if (x % 2 == 0) "success" else "failure" (x, prefix + x.toString) } } } object BigtableDoFnTest { val queue: ConcurrentLinkedQueue[Int] = new ConcurrentLinkedQueue[Int]() } class TestBigtableDoFn extends BigtableDoFn[Int, String](null) { override def newClient(): BigtableSession = null override def asyncLookup(session: BigtableSession, input: Int): ListenableFuture[String] = Futures.immediateFuture(input.toString) } class TestCachingBigtableDoFn extends BigtableDoFn[Int, String](null, 100, new TestCacheSupplier) { override def newClient(): BigtableSession = null override def asyncLookup(session: BigtableSession, input: Int): ListenableFuture[String] = { BigtableDoFnTest.queue.add(input) Futures.immediateFuture(input.toString) } } class TestFailingBigtableDoFn extends BigtableDoFn[Int, String](null) { override def newClient(): BigtableSession = null override def asyncLookup(session: BigtableSession, input: Int): ListenableFuture[String] = if (input % 2 == 0) { Futures.immediateFuture("success" + input) } else { Futures.immediateFailedFuture(new RuntimeException("failure" + input)) } } class TestCacheSupplier extends CacheSupplier[Int, String, java.lang.Long] { override def createCache(): Cache[java.lang.Long, String] = CacheBuilder.newBuilder().build[java.lang.Long, String]() override def getKey(input: Int): java.lang.Long = input.toLong }
Example 191
Source File: ScioUtil.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.util import java.net.URI import java.util.UUID import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.spotify.scio.ScioContext import org.apache.beam.sdk.extensions.gcp.options.GcpOptions import org.apache.beam.sdk.extensions.gcp.util.Transport import org.apache.beam.sdk.{PipelineResult, PipelineRunner} import org.slf4j.LoggerFactory import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} private[scio] object ScioUtil { @transient private lazy val log = LoggerFactory.getLogger(this.getClass) @transient lazy val jsonFactory = Transport.getJsonFactory def isLocalUri(uri: URI): Boolean = uri.getScheme == null || uri.getScheme == "file" def isRemoteUri(uri: URI): Boolean = !isLocalUri(uri) def isLocalRunner(runner: Class[_ <: PipelineRunner[_ <: PipelineResult]]): Boolean = { require(runner != null, "Pipeline runner not set!") // FIXME: cover Flink, Spark, etc. in local mode runner.getName == "org.apache.beam.runners.direct.DirectRunner" } def isRemoteRunner(runner: Class[_ <: PipelineRunner[_ <: PipelineResult]]): Boolean = !isLocalRunner(runner) def classOf[T: ClassTag]: Class[T] = implicitly[ClassTag[T]].runtimeClass.asInstanceOf[Class[T]] def getScalaJsonMapper: ObjectMapper = new ObjectMapper().registerModule(DefaultScalaModule) def addPartSuffix(path: String, ext: String = ""): String = if (path.endsWith("/")) s"${path}part-*$ext" else s"$path/part-*$ext" def getTempFile(context: ScioContext, fileOrPath: String = null): String = { val fop = Option(fileOrPath).getOrElse("scio-materialize-" + UUID.randomUUID().toString) val uri = URI.create(fop) if ((ScioUtil.isLocalUri(uri) && uri.toString.startsWith("/")) || uri.isAbsolute) { fop } else { val filename = fop val tmpDir = if (context.options.getTempLocation != null) { context.options.getTempLocation } else { val m = "Specify a temporary location via --tempLocation or PipelineOptions.setTempLocation." Try(context.optionsAs[GcpOptions].getGcpTempLocation) match { case Success(l) => log.warn( "Using GCP temporary location as a temporary location to materialize data. " + m ) l case Failure(_) => throw new IllegalArgumentException("No temporary location was specified. " + m) } } tmpDir + (if (tmpDir.endsWith("/")) "" else "/") + filename } } def pathWithShards(path: String): String = path.replaceAll("\\/+$", "") + "/part" }
Example 192
Source File: ScalaAsyncLookupDoFn.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.transforms import com.spotify.scio.transforms.BaseAsyncLookupDoFn.{CacheSupplier, NoOpCacheSupplier} import scala.concurrent.Future import scala.util.{Failure, Success, Try} abstract class ScalaAsyncLookupDoFn[A, B, C]( maxPendingRequests: Int, cacheSupplier: CacheSupplier[A, B, _] ) extends BaseAsyncLookupDoFn[A, B, C, Future[B], Try[B]](maxPendingRequests, cacheSupplier) with ScalaFutureHandlers[B] { def this() { this(1000, new NoOpCacheSupplier[A, B]) } def this(maxPendingRequests: Int) { this(maxPendingRequests, new NoOpCacheSupplier[A, B]) } override def success(output: B): Try[B] = Success(output) override def failure(throwable: Throwable): Try[B] = Failure(throwable) }
Example 193
Source File: OverrideTypeProviderFinder.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.bigquery.validation import scala.util.control.NonFatal import scala.util.{Failure, Success, Try} object OverrideTypeProviderFinder { var typeProvider: String = System.getProperty("override.type.provider", "") var provider: OverrideTypeProvider = instance() def instance(): OverrideTypeProvider = { // Load the class dynamically at compile time and runtime val classInstance = Try( Class .forName(System.getProperty("override.type.provider", "")) .getConstructor() .newInstance() .asInstanceOf[OverrideTypeProvider] ) classInstance match { case Success(value) => value case Failure(NonFatal(_)) => new DummyOverrideTypeProvider } } def getProvider: OverrideTypeProvider = { val thisInstance = System.getProperty("override.type.provider", "") if (typeProvider != thisInstance) { typeProvider = thisInstance provider = instance() } provider } }
Example 194
Source File: Futures.scala From courscala with Apache License 2.0 | 5 votes |
package org.coursera.common.concurrent import scala.concurrent.ExecutionContext import scala.concurrent.Future import scala.concurrent.Promise import scala.util.Failure import scala.util.Success import scala.util.Try import scala.util.control.NonFatal object Futures extends FutureExtractors { def findMatch[T, U]( futures: TraversableOnce[Future[T]]) (pf: PartialFunction[T, U]) (implicit ec: ExecutionContext): Future[Option[U]] = { Future.find(futures)(pf.isDefinedAt).map(_.map(pf)) } def option[T](option: Option[Future[T]])(implicit ec: ExecutionContext): Future[Option[T]] = option.map(_.map(Some(_))).getOrElse(Future.successful(None)) def map[K, V](m: Map[K, Future[V]])(implicit ec: ExecutionContext): Future[Map[K, V]] = { val elementFutures = m.map { case (key, valueFuture) => valueFuture.map(key -> _) } Future.sequence(elementFutures).map(_.toMap) } object Implicits { implicit class FutureOps[T](future: Future[T]) { def toTry(implicit ec: ExecutionContext): Future[Try[T]] = { future .map(Success.apply) .recover(PartialFunction(Failure.apply)) } } } }
Example 195
Source File: InfluxWriter.scala From burrower with MIT License | 5 votes |
package com.github.splee.burrower.write import com.github.splee.burrower.lag.LagGroup import com.paulgoldbaum.influxdbclient.{InfluxDB, Point} import com.paulgoldbaum.influxdbclient.Parameter.Precision import com.typesafe.scalalogging.LazyLogging import scala.compat.Platform._ import scala.concurrent.ExecutionContext.Implicits.global import scala.util.{Failure, Success} class InfluxWriter( influxHost: String, influxPort: Int, influxDatabase: String, influxSeries: String, userName: String, password: String, isSecure: Boolean ) extends Writer with LazyLogging { val influxdb = InfluxDB.connect(influxHost, influxPort, userName, password, isSecure) val database = influxdb.selectDatabase(influxDatabase) def write(lagGroup: LagGroup): Unit = { val points = lagGroup.lags.map(lag => { Point(influxSeries, lagGroup.timestamp) .addTag("cluster", lag.cluster) .addTag("consumer_group", lag.group) .addTag("topic", lag.topic) .addTag("partition", lag.partition.toString) .addField("offset", lag.offset) .addField("lag", lag.lag) }) database.bulkWrite(points, precision = Precision.MILLISECONDS) .onComplete(_ match { case Success(v) => logger.debug("Metrics sent to InfluxDB") case Failure(e) => logger.debug(f"Sending metrics to InfluxDB failed: ${e.getMessage}") }) } }
Example 196
Source File: BintrayHttp.scala From releaser with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.releaser.bintray import java.net.URL import java.nio.file.Path import java.util.concurrent.TimeUnit import akka.actor.ActorSystem import akka.stream.ActorMaterializer import play.api.libs.ws.ning.{NingAsyncHttpClientConfigBuilder, NingWSClient, NingWSClientConfig} import play.api.libs.ws.{WSAuthScheme, WSClientConfig, WSResponse} import play.api.mvc.Results import uk.gov.hmrc.{Logger, ServiceCredentials} import scala.concurrent.Await import scala.concurrent.duration.Duration import scala.util.{Failure, Success, Try} import scala.concurrent.duration._ class BintrayHttp(creds:ServiceCredentials) extends Logger { implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() private def getTimeoutPropertyOptional(key: String) = Option(System.getProperty(key)).map(_.toLong milliseconds) def wsClientConfig = NingWSClientConfig( wsClientConfig = WSClientConfig( connectionTimeout = getTimeoutPropertyOptional("wsclient.timeout.connection").getOrElse(2 seconds), idleTimeout = getTimeoutPropertyOptional("wsclient.timeout.idle").getOrElse(2 seconds), requestTimeout = getTimeoutPropertyOptional("wsclient.timeout.request").getOrElse(2 seconds) ) ) val ws = new NingWSClient(new NingAsyncHttpClientConfigBuilder(wsClientConfig).build()) def apiWs(url:String) = ws.url(url) .withAuth( creds.user, creds.pass, WSAuthScheme.BASIC) .withHeaders("content-type" -> "application/json") def emptyPost(url:String): Try[Unit] = { log.info(s"posting file to $url") val call = apiWs(url).post(Results.EmptyContent()) val result: WSResponse = Await.result(call, Duration.apply(5, TimeUnit.MINUTES)) result.status match { case s if s >= 200 && s < 300 => Success(new URL(url)) case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}")) } } def get[A](url:String): Try[String] ={ log.info(s"getting file from $url") val call = apiWs(url).get() val result: WSResponse = Await.result(call, Duration.apply(5, TimeUnit.MINUTES)) result.status match { case s if s >= 200 && s < 300 => Success(result.body) case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}")) } } def putFile(version: VersionDescriptor, file: Path, url: String): Try[Unit] = { log.info(s"version $version") log.info(s"putting file to $url") val call = apiWs(url) .withHeaders( "X-Bintray-Package" -> version.artefactName, "X-Bintray-Version" -> version.version) .put(file.toFile) val result: WSResponse = Await.result(call, Duration.apply(6, TimeUnit.MINUTES)) result.status match { case s if s >= 200 && s < 300 => Success(Unit) case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}")) } } }
Example 197
Source File: Sql.scala From ksql-streams with Apache License 2.0 | 5 votes |
package com.landoop.kstreams.sql.transform import com.landoop.sql.Field import org.apache.calcite.config.Lex import org.apache.calcite.sql.parser.SqlParser import org.apache.calcite.sql.{SqlIdentifier, SqlInsert, SqlSelect} import scala.util.{Failure, Success, Try} object Sql { private val config = SqlParser.configBuilder .setLex(Lex.MYSQL) .setCaseSensitive(false) .setIdentifierMaxLength(250) .build def parseSelect(sql: String): SelectTransformContext = { val withStructure: Boolean = sql.trim.toLowerCase().endsWith("withstructure") val query = if (withStructure) { sql.trim.dropRight("withstructure".length) } else sql val parser = SqlParser.create(query, config) Try(parser.parseQuery()) match { case Failure(e) => throw new IllegalArgumentException(s"Query is not valid.Needs to be `SELECT ... FROM $$sourceTopic`.${e.getMessage}") case Success(select: SqlSelect) => validate(select) SelectTransformContext( select.getFrom.asInstanceOf[SqlIdentifier].getSimple, Field.from(select), withStructure) case Success(other) => throw new IllegalArgumentException("Invalid statement. Needs to be `SELECT ... FROM $sourceTopic`") } } def validate(select: SqlSelect): Unit = { require(select.getFrom.isInstanceOf[SqlIdentifier], s"${select.getFrom} is not valid.") } def parseInsert(sql: String): TransformContext = { val withStructure: Boolean = sql.trim.toLowerCase().endsWith("withstructure") val query = if (withStructure) { sql.trim.dropRight("withstructure".length) } else sql val parser = SqlParser.create(query, config) Try(parser.parseQuery()) match { case Failure(e) => throw new IllegalArgumentException(s"Query is not valid.Needs to be `INSERT INTO A SELECT ... FROM A`.${e.getMessage}") case Success(sqlInsert: SqlInsert) => validate(sqlInsert) val target = sqlInsert.getTargetTable.asInstanceOf[SqlIdentifier].getSimple val sqlSource = sqlInsert.getSource.asInstanceOf[SqlSelect] TransformContext(target, sqlSource.getFrom.asInstanceOf[SqlIdentifier].getSimple, Field.from(sqlSource), withStructure) case Success(other) => throw new IllegalArgumentException("Invalid statement. Needs to be `INSERT INTO A SELECT ... FROM A`") } } def validate(insert: SqlInsert): Unit = { require(insert != null, "Null instances are invalid") require(insert.getTargetTable.isInstanceOf[SqlIdentifier], "Invalid target specified") insert.getSource match { case select: SqlSelect => validate(select) case other => throw new IllegalArgumentException("Invalid source. Needs to be a SELECT .. FROM A") } } } case class TransformContext(target: String, from: String, fields: Seq[Field], withStructure: Boolean) { require(target != null && target.nonEmpty, s"'$target' is not valid") require(from != null && from.nonEmpty, s"'$from' is not valid") require(fields != null && fields.nonEmpty, "You need to specify what fields you want to select") } case class SelectTransformContext(from: String, fields: Seq[Field], withStructure: Boolean) { require(from != null && from.nonEmpty, s"'$from' is not valid") require(fields != null && fields.nonEmpty, "You need to specify what fields you want to select") }
Example 198
Source File: BadDataHandler.scala From model-serving-tutorial with Apache License 2.0 | 5 votes |
package com.lightbend.modelserving.flink.wine import org.apache.flink.api.common.functions.FlatMapFunction import org.apache.flink.util.Collector import scala.util.{Failure, Success, Try} object BadDataHandler { def apply[T] = new BadDataHandler[T] } class BadDataHandler[T] extends FlatMapFunction[Try[T], T] { override def flatMap(t: Try[T], out: Collector[T]): Unit = { t match { case Success(t) => out.collect(t) case Failure(e) => println(s"BAD DATA: ${e.getMessage}") } } }
Example 199
Source File: Global.scala From cave with MIT License | 5 votes |
import scala.concurrent.Future
import scala.util.{Failure, Success}
import init.Init
import org.apache.commons.logging.LogFactory
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
object Global extends GlobalSettings {
private[this] final val Log = LogFactory.getLog(this.getClass)
override def onHandlerNotFound(request: RequestHeader) = {
Future.successful(NotFound)
}
override def onBadRequest(request: RequestHeader, error: String) = {
Future.successful(BadRequest("Bad Request: " + error))
}
override def onError(request: RequestHeader, ex: Throwable) = {
Logger.error(ex.toString, ex)
Future.successful(InternalServerError(ex.toString))
}
override def onStart(app: Application) {
Init.start()
}
override def onStop(app: Application) {
Init.shutdown()
}
}
Example 200
Source File: PagerdutyNotifications.scala From sundial with MIT License | 5 votes |
package service.notifications import java.util.UUID import dao.SundialDaoFactory import model.{PagerdutyNotification, Process, ProcessStatusType} import play.api.Logging import play.api.libs.ws.WSClient import speedwing.pagerduty.api.v0.Client import speedwing.pagerduty.api.v0.models.{CreateEvent, EventType} import scala.util.{Failure, Success} class PagerdutyNotifications(wsClient: WSClient, daoFactory: SundialDaoFactory) extends Notification with Logging { private final val PagerdutyPageMessage = "The Sundial Job %s, has failed at least %s time(s) in a row." override def notifyProcessFinished(processId: UUID): Unit = daoFactory.withSundialDao { implicit dao => for { process <- dao.processDao.loadProcess(processId) processDef <- dao.processDefinitionDao.loadProcessDefinition( process.processDefinitionName) } yield { val pagerdutyNotifications = processDef.notifications.collect { case pagerduty: PagerdutyNotification => pagerduty } if (pagerdutyNotifications.nonEmpty) { val maxNumFailures = pagerdutyNotifications.map(_.numConsecutiveFailures).max val recentProcesses: Seq[Process] = dao.processDao.findProcesses(processDefinitionName = Some(process.processDefinitionName), limit = Some(maxNumFailures)) val numConsecutiveFailedProcesses = getNumberConsecutiveFailures(recentProcesses) processPagerdutyNotifications(process, pagerdutyNotifications, numConsecutiveFailedProcesses) } } } private def processPagerdutyNotifications( process: Process, pagerdutyNotifications: Seq[PagerdutyNotification], numConsecutiveFailedProcesses: Int) = { import scala.concurrent.ExecutionContext.Implicits.global pagerdutyNotifications.foreach(pagerdutyNotification => { if (numConsecutiveFailedProcesses >= pagerdutyNotification.numConsecutiveFailures) { val createEvent = CreateEvent( pagerdutyNotification.serviceKey, EventType.Trigger, incidentKey = None, Some( PagerdutyPageMessage.format( process.processDefinitionName, pagerdutyNotification.numConsecutiveFailures.toString)), None, Some("Sundial"), None ) val pagerdutyClient = new Client(wsClient, pagerdutyNotification.apiUrl) val pagerdutyRequest = pagerdutyClient.createEvents.post(createEvent) pagerdutyRequest.onComplete { case Success(pageId) => logger.info( s"Successfully submitted Pagerduty request with Id [${pageId.incidentKey}]") case Failure(e) => logger.error(s"Failed to submit Pagerduty request", e) } } }) } private def getNumberConsecutiveFailures(recentProcesses: Seq[Process]): Int = recentProcesses .takeWhile(_.status.statusType == ProcessStatusType.Failed) .size }