java.nio.file.NoSuchFileException Scala Examples

The following examples show how to use java.nio.file.NoSuchFileException. 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: MavenCoordinatesListReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.utils

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, NoSuchFileException, Path}

import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wixpress.build.maven.MavenCoordinatesListReader
import com.wixpress.build.maven.MavenMakers.someCoordinates
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class MavenCoordinatesListReaderIT extends SpecificationWithJUnit{
  "MavenCoordinatesListReader" should {
    "read file with coordinates" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                            |${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA,coordinatesB)
    }

    "ignore empty line" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                           |
                           |${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA,coordinatesB)
    }

    "ignore preceding and trailing spaces" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"    ${coordinatesA.serialized}   "
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA)
    }

    "ignore lines that starts with #" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                            |#${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA)
    }

    "throw exception in case file is missing" in new Ctx{
      MavenCoordinatesListReader.coordinatesIn(fs.getPath("non-existing-file")) must throwA[NoSuchFileException]
    }
  }

  trait Ctx extends Scope{
    val fs = MemoryFileSystemBuilder.newLinux().build()
    def fileWithContent(content:String):Path = {
      val path = Files.createTempFile(fs.getPath("/"),"",".txt")
      Files.write(path, content.getBytes(StandardCharsets.UTF_8))
    }
  }

} 
Example 2
Source File: ScriptManagerTest.scala    From codepropertygraph   with Apache License 2.0 5 votes vote down vote up
package io.shiftleft.console.scripting

import better.files.File
import cats.effect.IO
import org.scalatest.{Inside, Matchers, WordSpec}

import io.shiftleft.codepropertygraph.Cpg
import io.shiftleft.console.scripting.ScriptManager.{ScriptCollections, ScriptDescription, ScriptDescriptions}

import java.nio.file.{FileSystemNotFoundException, NoSuchFileException, Path}

import scala.io.Source
import scala.util.Try

class ScriptManagerTest extends WordSpec with Matchers with Inside {

  private object TestScriptExecutor extends AmmoniteExecutor {
    override protected def predef: String = ""
    override def runScript(scriptPath: Path, parameters: Map[String, String], cpg: Cpg): IO[Any] = IO.fromTry(
      Try {
        val source = Source.fromFile(scriptPath.toFile)
        val result = source.getLines.mkString(System.lineSeparator())
        source.close()
        result
      }
    )
  }

  private object TestScriptManager extends ScriptManager(TestScriptExecutor)

  protected val DEFAULT_CPG_NAME: String = {
    if (File(".").name == "console") {
      (File("..") / "resources" / "testcode" / "cpgs" / "method" / "cpg.bin.zip").pathAsString
    } else {
      (File("resources") / "testcode" / "cpgs" / "method" / "cpg.bin.zip").pathAsString
    }
  }

  def withScriptManager(f: ScriptManager => Unit): Unit = {
    f(TestScriptManager)
  }

  "listing scripts" should {
    "be correct" in withScriptManager { scriptManager =>
      val scripts = scriptManager.scripts()
      val expected = List(
        ScriptCollections("general",
                          ScriptDescriptions(
                            "A collection of general purpose scripts.",
                            List(ScriptDescription("list-funcs.sc", "Lists all functions."))
                          )),
        ScriptCollections("java",
                          ScriptDescriptions(
                            "A collection of java-specific scripts.",
                            List(ScriptDescription("list-sl-ns.sc", "Lists all shiftleft namespaces."))
                          )),
        ScriptCollections("general/general_plus",
                          ScriptDescriptions(
                            "Even more general purpose scripts.",
                            List.empty
                          ))
      )

      scripts should contain theSameElementsAs expected
    }
  }

  "running scripts" should {
    "be correct when explicitly specifying a CPG" in withScriptManager { scriptManager =>
      val expected =
        """|@main def main() = {
           |  cpg.method.name.l
           |}""".stripMargin

      scriptManager.runScript("general/list-funcs.sc", Map.empty, Cpg.emptyCpg) shouldBe expected
    }

    "be correct when specifying a CPG filename" in withScriptManager { scriptManager =>
      val expected =
        """|@main def main() = {
           |  cpg.method.name.l
           |}""".stripMargin

      scriptManager.runScript("general/list-funcs.sc", Map.empty, DEFAULT_CPG_NAME) shouldBe expected
    }

    "throw an exception if the specified CPG can not be found" in withScriptManager { scriptManager =>
      intercept[FileSystemNotFoundException] {
        scriptManager.runScript("general/list-funcs.sc", Map.empty, "cake.bin.zip")
      }
    }

    "throw an exception if the specified script can not be found" in withScriptManager { scriptManager =>
      intercept[NoSuchFileException] {
        scriptManager.runScript("list-funcs.sc", Map.empty, Cpg.emptyCpg)
      }
    }
  }

} 
Example 3
Source File: FileMonitorActor.scala    From graphql-gateway   with Apache License 2.0 5 votes vote down vote up
package sangria.gateway.file

import java.nio.file.{NoSuchFileException, StandardWatchEventKinds}

import akka.actor.{Actor, ActorRef, Cancellable, PoisonPill, Props}
import akka.event.Logging
import better.files._
import sangria.gateway.file.FileWatcher._

import scala.collection.mutable
import scala.concurrent.duration.FiniteDuration

class FileMonitorActor(paths: Seq[File], threshold: FiniteDuration, globs: Seq[String], cb: Vector[File] ⇒ Unit) extends Actor {
  import FileMonitorActor._

  import context.dispatcher

  val log = Logging(context.system, this)
  var watchers: Seq[ActorRef] = _
  val pendingFiles: mutable.HashSet[File] = mutable.HashSet[File]()
  var scheduled: Option[Cancellable] = None

  override def preStart(): Unit = {
    watchers = paths.map(_.newWatcher(recursive = true))

    watchers.foreach { watcher ⇒
      watcher ! when(events = StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE) {
        case (_, file) ⇒ self ! FileChange(file)
      }
    }
  }

  def receive = {
    case FileChange(file) ⇒
      try {
        if (file.exists && !file.isDirectory && globs.exists(file.glob(_, includePath = false).nonEmpty)) {
          pendingFiles += file

          if (scheduled.isEmpty)
            scheduled = Some(context.system.scheduler.scheduleOnce(threshold, self, Threshold))
        }
      } catch {
        case _: NoSuchFileException ⇒ // ignore, it's ok
      }

    case Threshold ⇒
      val files = pendingFiles.toVector.sortBy(_.name)

      if (files.nonEmpty)
        cb(files)

      pendingFiles.clear()
      scheduled = None
  }
}

object FileMonitorActor {
  case class FileChange(file: File)
  case object Threshold

  def props(paths: Seq[File], threshold: FiniteDuration, globs: Seq[String], cb: Vector[File] ⇒ Unit) =
    Props(new FileMonitorActor(paths, threshold, globs, cb))
} 
Example 4
Source File: FileParamStoreTest.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.paramstore

import java.nio.file.NoSuchFileException

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

class FileParamStoreTest extends AnyFunSuite with Matchers {

  test("Can be used to retrieve a property from file") {
    //TODO: Implement
  }

  test("Non existing file trows an exception") {
    //TODO: Implement
  }

  test("Non existing config path trows an exception") {
    //TODO: Implement
  }

  test("Non existing key trows an exception") {
    //TODO: Implement
  }

  test("Validation happens at call, not at retrieval") {
    val store    = new FileParamStore("/some/unexisting/file/path")
    val function = store.lookup("some.key")

    an[NoSuchFileException] should be thrownBy function.apply()
  }
} 
Example 5
Source File: KubectlActionExecutor.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.installer

import java.nio.file.NoSuchFileException

import akka.actor.ActorSystem
import akka.stream._

import scala.concurrent._

import akka.event.LoggingAdapter

trait ActionExecutor {
  def execute(
      action: Action
  )(implicit
    system: ActorSystem,
    materializer: Materializer,
    ec: ExecutionContext,
    log: LoggingAdapter,
    settings: Settings): Future[ActionResult]
}

case object KubectlActionExecutor extends ActionExecutor {
  override def execute(
      action: Action
  )(implicit
    system: ActorSystem,
    materializer: Materializer,
    ec: ExecutionContext,
    log: LoggingAdapter,
    settings: Settings): Future[ActionResult] =
    action.execute().recover {
      case actionFailure: ActionFailure =>
        actionFailure
      case exception: NoSuchFileException =>
        ActionFailure(action, 1, Some(s"Cannot find file '${exception.getMessage}"))
      case exception: Exception =>
        ActionFailure(action, 1, Some(exception.getMessage))
    }
}