• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Paths类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.nio.file.Paths的典型用法代码示例。如果您正苦于以下问题:Scala Paths类的具体用法?Scala Paths怎么用?Scala Paths使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Paths类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: DirectoryIndex

//设置package包名称以及导入依赖的类
package index

import java.io.File
import java.nio.file.{Files, Paths}

import util.{NotADirectoryException, NotAFileException}


case class DirectoryIndex(private val directory: File)(private implicit val homeDirPath: String) extends Index(directory) {
  override val handler: File = {
    if (!directory.exists || directory.isFile) throw NotADirectoryException(directory)
    directory
  }
  override val path: String = Paths.get(homeDirPath).relativize(Paths.get(handler.getCanonicalPath)).toString
  val subFiles: List[FileIndex] = handler.listFiles.filter(_.isFile).map(FileIndex(_)(homeDirPath)).toList
  val subDirectories: List[DirectoryIndex] = handler.listFiles.filter(_.isDirectory).map(DirectoryIndex(_)(homeDirPath)).toList

  override def find(fileName: String): List[_ <: Index] = {
    (subFiles ++ subDirectories).map(_.find(fileName)).fold(super.find(fileName))(_ ++ _)
  }
}

object DirectoryIndex {
  def apply(directoryName: String)(implicit homeDirPath: String): DirectoryIndex = {
    DirectoryIndex(new File(directoryName))(homeDirPath)
  }
} 
开发者ID:mprzewie,项目名称:cloudia-utils,代码行数:28,代码来源:Index.scala


示例2: ExportModel

//设置package包名称以及导入依赖的类
package com.cloudera.datascience.cdsw.acme

import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption._
import java.nio.file.{Files, Paths}
import javax.xml.transform.stream.StreamResult

import org.dmg.pmml.Application
import org.jpmml.model.JAXBUtil
import org.jpmml.sparkml.ConverterUtil

import acme.ACMEModel

object ExportModel {
  
  def main(args: Array[String]): Unit = {
    val training = ACMEData.readData()
    val pipeline = ACMEModel.buildModel()
    
    val pmml = ConverterUtil.toPMML(training.schema, pipeline)
    pmml.getHeader.setApplication(new Application("ACME Occupancy Detection"))
    
    val modelPath = Paths.get("src", "main", "resources")
    if (!Files.exists(modelPath)) {
      Files.createDirectory(modelPath)
    }
    val pmmlFile = modelPath.resolve("model.pmml")
    val writer = Files.newBufferedWriter(pmmlFile, StandardCharsets.UTF_8, WRITE, CREATE, TRUNCATE_EXISTING)
    try {
      JAXBUtil.marshalPMML(pmml, new StreamResult(writer))
    } finally {
      writer.close()
    }
  }

} 
开发者ID:srowen,项目名称:cdsw-simple-serving,代码行数:37,代码来源:ExportModel.scala


示例3: runJavaClassInDebugMode

//设置package包名称以及导入依赖的类
package com.github.unknownnpc.remotedebugtool.util

import java.io.File
import java.nio.file.Paths

import com.github.unknownnpc.remotedebugtool.domain.Port
import org.slf4j.LoggerFactory

import scala.sys.process._

trait JdkDebugProcessUtil {

  def runJavaClassInDebugMode(javaClassName: String,
                              debugPort: Port,
                              args: String = "",
                              javaPath: String = "java"): Process = {

    val log = LoggerFactory.getLogger(this.getClass)

    val runJavaClassCommand = Seq(
      s"$javaPath"
      , "-Xdebug"
      , s"-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$debugPort"
      , s"$javaClassName"
      , s"$args"
    )

    val processLog = ProcessLogger(message => log.debug(s"External process message: [$message]"))
    Process(
      tuneCommandForMultiplatform(runJavaClassCommand),
      new File(absolutePathToResourceFolderBy("/jdi"))
    ).run(processLog)
  }

  private def absolutePathToResourceFolderBy(name: String) = {
    val resource = getClass.getResource(name)
    Paths.get(resource.toURI).toFile.getAbsolutePath
  }

  private def tuneCommandForMultiplatform(command: Seq[String]) = {
    val os = sys.props("os.name").toLowerCase
    os match {
      case x if x contains "windows" => Seq("cmd", "/C") ++ command
      case _ => command
    }
  }

} 
开发者ID:UnknownNPC,项目名称:remote-debug-tool,代码行数:49,代码来源:JdkDebugProcessUtil.scala


示例4: ProvisionUser

//设置package包名称以及导入依赖的类
// Copyright (c) 2017 Grier Forensics. All Rights Reserved.

package com.grierforensics.greatdane.connector

import java.net.URI
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.apache.commons.io.IOUtils
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients


object ProvisionUser {
  def main(args: Array[String]): Unit = {

    def die = {
      println("Usage: provision-user <email-address> [<certificate file>]")
      sys.exit(1)
    }
    val (emailAddress, certPem) = args.toList match {
      case email :: tail => tail match {
        case Nil => (email, "")
        case certFile :: Nil => (email, new String(Files.readAllBytes(Paths.get(certFile)), StandardCharsets.UTF_8))
        case _ => die
      }
      case _ => die
    }

    val client = HttpClients.createDefault()
    val uri = new URI(s"http://${Settings.Host}:${Settings.Port}/api/v1/user/$emailAddress")
    val post = new HttpPost(uri)
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    post.addHeader(HttpHeaders.AUTHORIZATION, Settings.ApiKey)
    println(post.toString)

    val req = ProvisionRequest(None, if (certPem.length > 0) Some(Seq(certPem)) else None)
    val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
    val json = mapper.writeValueAsString(req)
    println(json)

    post.setEntity(new StringEntity(json))

    val resp = client.execute(post)
    try {
      val entity = resp.getEntity
      println(resp.getStatusLine.getStatusCode, resp.getStatusLine.getReasonPhrase)
      println(IOUtils.toString(entity.getContent, StandardCharsets.UTF_8))
    } finally {
      resp.close()
    }

  }
} 
开发者ID:grierforensics,项目名称:Great-DANE-Connector,代码行数:59,代码来源:ProvisionUser.scala


示例5: WaitForTwoFlowsToComplete

//设置package包名称以及导入依赖的类
package tutorial


import java.nio.file.Paths

import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl._
import akka.util.ByteString
import akka.{Done, NotUsed}

import scala.concurrent._

object WaitForTwoFlowsToComplete {

  def main(args: Array[String]) = {

    implicit val system = ActorSystem("WaitForTwoFlowsToComplete")
    implicit val ec = system.dispatcher
    implicit val materializer = ActorMaterializer()

    val source: Source[Int, NotUsed] = Source(1 to 100)

    val f1Fut: Future[Done] = source.runForeach(i => println(i))

    //declaration of what happens when we scan (= transform) the source
    val factorials: Source[BigInt, NotUsed] = source.scan(BigInt(1))((acc, next) => acc * next)
    val f2fut: Future[IOResult] =
      factorials
        .map(num => ByteString(s"$num\n"))
        .runWith(FileIO.toPath(Paths.get("factorials.txt")))

    val aggFut = for {
      f1Result <- f1Fut
      f2Result <- f2fut
    } yield (f1Result, f2Result)

    aggFut.onComplete {  results =>
      println("Resulting futures from flows completed with results: " + results + " - about to terminate")
      system.terminate()
    }}
} 
开发者ID:pbernet,项目名称:akka_streams_tutorial,代码行数:43,代码来源:WaitForTwoFlowsToComplete.scala


示例6: WaitForThreeFlowsToComplete

//设置package包名称以及导入依赖的类
package tutorial

import java.nio.file.Paths

import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl._
import akka.util.ByteString
import akka.{Done, NotUsed}

import scala.concurrent.duration._

import scala.concurrent._

object WaitForThreeFlowsToComplete {

  def main(args: Array[String]) = {

    implicit val system = ActorSystem("WaitForThreeFlowsToComplete")
    implicit val ec = system.dispatcher
    implicit val materializer = ActorMaterializer()

    def reusableLineSink(filename: String): Sink[String, Future[IOResult]] =
      Flow[String]
        .map(s => ByteString(s + "\n"))
        //Keep.right means: we want to retain what the FileIO.toPath sink has to offer
        .toMat(FileIO.toPath(Paths.get(filename)))(Keep.right)


    val source: Source[Int, NotUsed] = Source(1 to 100)

    val f1Fut: Future[Done] = source.runForeach(i => println(i))

    //declaration of what happens when we scan (= transform) the source
    val factorials = source.scan(BigInt(1))((acc, next) => acc * next)
    val f2fut: Future[IOResult] = factorials.map(_.toString).runWith(reusableLineSink("factorial2.txt"))

    val f3fut = factorials
      .zipWith(Source(0 to 10))((num, idx) => s"$idx! = $num")
      .throttle(1, 1.second, 1, ThrottleMode.shaping)
      .runWith(reusableLineSink("factorial3.txt"))

    val aggFut = for {
      f1Result <- f1Fut
      f2Result <- f2fut
      f3Result <- f3fut
    } yield (f1Result, f2Result, f3Result)

    aggFut.onComplete{  results =>
      println("Resulting Futures from Flows completed with results: " + results + " - about to terminate")
      system.terminate()
    }}
} 
开发者ID:pbernet,项目名称:akka_streams_tutorial,代码行数:54,代码来源:WaitForThreeFlowsToComplete.scala


示例7: LogBack

//设置package包名称以及导入依赖的类
package gitbucket.monitoring.services

import java.nio.file.{Files, Paths}
import scala.xml.XML
import gitbucket.core.util.StringUtil
import gitbucket.monitoring.models.{LogBackInfo}
import gitbucket.monitoring.utils._

object LogBack {
  val notFoundMessage = "Can not find logback configuration file."
  val dosentConfigureMessage = "Dosen't configure Logback."
  val enableLogging = Java.getSystemProperties.contains("logback.configurationFile")
  val confPath = Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage)
  val logBackSettingsFile: Either[String, String] = {
    if (enableLogging) {
      try {
        val bytes = Files.readAllBytes(Paths.get(confPath))
        (Right(
          StringUtil.convertFromByteArray(bytes)
        ))
      } catch {
        case e: Exception => Left(Message.error)
      }
    } else {
      Left(dosentConfigureMessage)
    }
  }

  val logFilePath: Either[String, String] = {
    if (enableLogging) {
      try {
        val xml = logBackSettingsFile match {
          case Left(message) => message
          case Right(s) => {
            (XML.loadString(s) \\ "appender" \ "file" toString).replace("<file>","").replace("</file>","")
          }
        }
        if (xml.trim.length == 0) {
          Left(Message.notFound)
        } else {
          Right(xml)
        }
      } catch {
        case e: Exception => Left(Message.error)
      }
    } else {
      Left(dosentConfigureMessage)
    }
  }

  def getLogBackSettings: LogBackInfo = {
    LogBackInfo(
      Java.getSystemProperties.contains("logback.configurationFile"),
      Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage),
      logFilePath
    )
  }
} 
开发者ID:YoshinoriN,项目名称:gitbucket-monitoring-plugin,代码行数:59,代码来源:LogBack.scala


示例8: DataUseLogger

//设置package包名称以及导入依赖的类
package se.gigurra.dcs.remote.util

import java.nio.file.{Files, Paths, StandardOpenOption}
import java.util.concurrent.atomic.AtomicLong
import com.twitter.finagle.util.DefaultTimer
import com.twitter.io.Charsets
import com.twitter.util.Duration
import scala.util.Try
import scala.collection.JavaConversions._

case class DataUseLogger(outputFilePath: String, dtFlush: Duration, enabled: Boolean) {

  private val atomicDelta = new AtomicLong(0L)
  private val path = Paths.get(outputFilePath)

  if (enabled) {
    DefaultTimer.twitter.schedule(dtFlush) {
      val delta = atomicDelta.getAndSet(0)
      val prevBytes = Try(Files.readAllLines(path, Charsets.Utf8).head.toLong).getOrElse(0L)
      val newVal = ((prevBytes + delta).toString + "\n").getBytes(Charsets.Utf8)
      Files.write(path, newVal, StandardOpenOption.WRITE, StandardOpenOption.CREATE)
    }
  }

  def log(nBytes: Long): Unit = {
    atomicDelta.addAndGet(nBytes)
  }

} 
开发者ID:GiGurra,项目名称:dcs-remote2,代码行数:30,代码来源:DataUseLogger.scala


示例9: ClientArtifactsTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import java.nio.file.{Files, Paths}

import com.twitter.finagle.http.Status

class ClientArtifactsTests extends TestBase {

  "Client Artifacts" should {

    "upload an artifact without a path" in {
      val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
      whenReady( client.uploadArtifact(bytes, "marathon.jpg") ) { result =>
        result._1 shouldBe(Status.Created)
        result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/marathon.jpg" ) )
      }
    }

    "upload an artifact with a path" in {
      val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
      whenReady( client.uploadArtifact(bytes, "marathon.jpg", Some("this/is/a/path/marathon.jpg")) ) { result =>
        result._1 shouldBe(Status.Created)
        result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/this/is/a/path/marathon.jpg" ) )
      }
    }

    "get an uploaded artifact" in {
      whenReady( client.getArtifact("marathon.jpg") ) { data =>
        val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
        bytes shouldBe( data )
      }
      whenReady( client.getArtifact("this/is/a/path/marathon.jpg") ) { data =>
        val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
        bytes shouldBe( data )
      }
    }

    "delete an artifact" in {
      whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg") ) { status =>
        status shouldBe( Status.Ok )
        whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg").failed ) { ex =>
          ex shouldBe a[MarathonClientException]
          ex.asInstanceOf[MarathonClientException].status shouldBe (Status.NotFound)
        }
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:51,代码来源:ClientArtifactsTests.scala


示例10: TorrentFileManagerTest_LargeFile

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent.l.file

import org.scalatest.FunSuite
import java.io.File
import com.spooky.bittorrent.metainfo.Torrents
import java.nio.file.Paths

class TorrentFileManagerTest_LargeFile extends FunSuite {
  val file = new File("O:\\tmp\\file.dump.torrent")
  val torrent = Torrents(file)
  val root = Paths.get("O:\\tmp")
  lazy val stat = new FileInitiator2(torrent, root).state()

  test("xx") {
    val fm = TorrentFileManager(torrent, root, stat)
  }

}
object TorrentFileManagerTest_LargeFilex {
  val file = new File("O:\\tmp\\file.dump.torrent")
  val torrent = Torrents(file)
  val root = Paths.get("O:\\tmp")
  lazy val stat = new FileInitiator2(torrent, root).state()
  def main(args: Array[String]) {
    val fm = TorrentFileManager(torrent, root, stat)
    assert(fm.complete)
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:29,代码来源:TorrentFileManager_LargeFile.scala


示例11: prepareFiles

//设置package包名称以及导入依赖的类
package controllers

import java.io.File
import java.nio.charset.Charset
import java.nio.file.{Files, Paths}
import java.util

trait FilePreparator {
  def prepareFiles() {
    if (Paths.get(TestEnv.TMP_FOLDER).toFile.exists() && Paths.get(TestEnv.TMP_FOLDER + TestEnv.TMP_FILE).toFile.exists()) return;
    var res1 = util.Arrays.asList("<testresult name=\"Test 1\" time=\"0\" tests=\"4\" errors = \"0\" skipped=\"0\" failures=\"0\"></testresult>")
    var res2 = util.Arrays.asList("<testresult name=\"Test 2\" time=\"0\" tests=\"4\" errors = \"0\" skipped=\"0\" failures=\"99\"></testresult>")
    Files.createDirectories(Paths.get(TestEnv.TMP_FOLDER));
    Files.write(Paths.get(TestEnv.TMP_FOLDER + TestEnv.TMP_FILE), res1, Charset.forName("UTF-8"))
    Files.write(Paths.get(TestEnv.TMP_FOLDER + "2"+TestEnv.TMP_FILE), res2, Charset.forName("UTF-8"))
  }

  def deleteFiles():Boolean = {
    var dir = new File(TestEnv.TMP_FOLDER)
    dir.listFiles.foreach(_.delete())
    dir.delete()
  }
} 
开发者ID:olka,项目名称:test-reports-agregator,代码行数:24,代码来源:FilePreparator.scala


示例12: Cacher

//设置package包名称以及导入依赖的类
package unus.helpers

import java.nio.file.{Files, Paths}

import org.apache.spark.rdd.RDD

import scala.reflect.ClassTag

abstract class Cacher[T: ClassTag] {
  protected val name: String
  protected def build(): RDD[T]

  private lazy val directory: String = Conf.cacheDir + "/" + name + "/"

  lazy val value: RDD[T] = {
    if (! cached) {
      save(build())
    }
    load().cache()
  }

  protected def load(): RDD[T] = {
    Conf.spark.sparkContext.objectFile(directory)
  }

  protected def save(data: RDD[T]): Unit = {
    data.saveAsObjectFile(directory)
  }

  protected def cached: Boolean = {
    Files.exists(Paths.get(directory))
  }
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:34,代码来源:Cacher.scala


示例13: Config

//设置package包名称以及导入依赖的类
package util

import java.io.File
import java.nio.file.{Path, Paths}

import com.typesafe.config.{Config => TypeSafeConfig, ConfigFactory}
import net.ceedubs.ficus.Ficus._


object Config {
  final private[this] var config: TypeSafeConfig = ConfigFactory.load()

  def set(configFile: File): Unit = {
    config = ConfigFactory.load(ConfigFactory.parseFile(configFile))
  }

  private val defaultPath: String = "src/main/resources"

  final lazy val resourcesDir: String = {
    val path: String = config.as[Option[String]]("resourcesDir").getOrElse(defaultPath)
    val dir: File = new File(path)
    if (dir.canRead && dir.isDirectory) {
      dir.toString
    } else {
      defaultPath
    }
  }

  def resourceFile(filename: String*): Path = {
    val file: File = Paths.get(resourcesDir, filename: _*).toAbsolutePath.toFile
    if (file.canRead && file.isFile) {
      file.toPath
    } else {
      Paths.get(defaultPath, filename: _*).toAbsolutePath
    }
  }

  final lazy val nGram: Int = config.as[Option[Int]]("concept.nGram.n") match {
    case Some(n) if 1 <= n =>
      n
    case _ =>
      1
  }

  final lazy val nGramGap: Int = config.as[Option[Int]]("concept.nGram.gap") match {
    case Some(gap) if 0 <= gap =>
      gap
    case Some(gap) if gap < 0 =>
      Int.MaxValue
    case _ =>
      0
  }

  final lazy val tokenizer: String = config.as[Option[String]]("concept.tokenizer").getOrElse("CharacterNGram")
} 
开发者ID:ynupc,项目名称:scalastringcourseday7,代码行数:56,代码来源:Config.scala


示例14: Command

//设置package包名称以及导入依赖的类
package tech.artemisia.core

import java.nio.file.Paths
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.joran.JoranConfigurator
import com.typesafe.config.Config
import org.slf4j.LoggerFactory
import tech.artemisia.config.{AppContext, AppSetting}
import tech.artemisia.core.dag.{ActorSysManager, Dag}
import tech.artemisia.task.TaskContext
import tech.artemisia.util.HoconConfigUtil.Handler



object Command {

  private def prepareAppContext(cmd_line_params: AppSetting) = {
    val appContext = new AppContext(cmd_line_params)
    configureLogging(appContext)
    AppLogger debug s"workflow_id: ${appContext.runId}"
    AppLogger debug s"working directory: ${appContext.workingDir}"
    if (appContext.globalConfigFile.nonEmpty) {
      AppLogger debug s"global config file: ${appContext.globalConfigFile.get}"
    }
    TaskContext.setWorkingDir(Paths.get(appContext.workingDir))
    TaskContext.predefinedConnectionProfiles = TaskContext.parseConnections(
      appContext.payload.as[Config](Keywords.Config.CONNECTION_SECTION))
    appContext
  }


  private def configureLogging(app_context: AppContext) = {
      val context = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
      val jc = new JoranConfigurator
      jc.setContext(context)
      context.reset()
      context.putProperty("log.console.level", app_context.logging.console_trace_level)
      context.putProperty("log.file.level", app_context.logging.file_trace_level)
      context.putProperty("env.working_dir", app_context.coreSetting.working_dir)
      context.putProperty("workflow_id", app_context.runId)
      jc.doConfigure(this.getClass.getResourceAsStream("/logback_config.xml"))
  }


  def run(cmd_line_params: AppSetting) = {
    AppLogger info "request for run command acknowledged"
    val app_context = prepareAppContext(cmd_line_params)
    AppLogger debug "context object created"
    TaskContext.setWorkingDir(Paths.get(app_context.workingDir))
    val dag = Dag(app_context)
    AppLogger debug "starting Actor System"
    val actor_sys_manager =  new ActorSysManager(app_context)
    val workers = actor_sys_manager.createWorker(Keywords.ActorSys.CUSTOM_DISPATCHER)
    val dag_player = actor_sys_manager.createPlayer(dag,workers)
    dag_player ! 'Play
  }

  def doc(cmd_line_params: AppSetting) = {
  }

} 
开发者ID:gitter-badger,项目名称:artemisia,代码行数:62,代码来源:Command.scala


示例15: HanaActivatorTester

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, File, FileWriter}
import java.nio.file.{Files, Paths}


object HanaActivatorTester {
  private val extensions = List("xsapp",
    "xsprivileges",
    "hdbstructure",
    "hdbprocedure",
    "xsjslib",
    "html",
    "hdbrole",
    "xsaccess")

  def main(args: Array[String]): Unit = {
    val workPath = Paths.get(".").toAbsolutePath.normalize.toString
    val filename = "dummy"
    extensions.foreach {
      e =>
        val helloPath = workPath + File.separator + filename + "." + e
        val bw = new BufferedWriter(new FileWriter(new File(helloPath), true))
        bw.write(" ")
        bw.close()
    }
    val workDir = new File(workPath)
    val orderedExtension = workDir.listFiles.toList.sorted(new HanaExtensionComparator)
    extensions.foreach { e =>
      val helloPath = workPath + File.separator + filename + "." + e
      Files.deleteIfExists(Paths.get(helloPath))
    }
  }
} 
开发者ID:janosbinder,项目名称:hana-activator,代码行数:33,代码来源:HanaActivatorTester.scala


示例16: DockerEnvironment

//设置package包名称以及导入依赖的类
package codacy.dockerApi

import java.nio.file.{Files, Paths}

import codacy.dockerApi.api.CodacyConfiguration
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, Json}

import scala.util.{Failure, Success, Try}

object DockerEnvironment {

  def config: Try[CodacyConfiguration] = Try(Files.readAllBytes(configFilePath)).transform(
    raw => Try(Json.parse(raw)).flatMap(
      _.validate[CodacyConfiguration].fold(
        asFailure,
        conf => Success(conf)
      )),
    error => Failure(error)
  )

  private[this] def asFailure(error: Seq[(JsPath, Seq[ValidationError])]) =
    Failure(new Throwable(Json.stringify(JsError.toFlatJson(error.toList))))

  private[this] lazy val configFilePath = sourcePath.resolve(".codacyrc")

  lazy val sourcePath = Paths.get("/src")
} 
开发者ID:codacy,项目名称:codacy-duplication-scala-seed,代码行数:29,代码来源:DockerEnvironment.scala


示例17: MultipartFormDataWritable

//设置package包名称以及导入依赖的类
package de.zalando.play.controllers

import java.nio.file.{ Files, Paths }

import akka.util.ByteString
import play.api.http.{ HeaderNames, Writeable }
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{ Codec, MultipartFormData }


object MultipartFormDataWritable {

  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]): ByteString = {
    val dataParts = data.flatMap {
      case (key, values) =>
        values.map { value =>
          val name = s""""$key""""
          s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
        }
    }.mkString("")
    val bytes: ByteString = Codec.utf_8.encode(dataParts)
    bytes
  }

  def filePartHeader(file: FilePart[TemporaryFile]): ByteString = {
    val name = s""""${file.key}""""
    val filename = s""""${file.filename}""""
    val contentType = file.contentType.map { ct =>
      s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
    }.getOrElse("")
    Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
  }

  val singleton = Writeable[MultipartFormData[TemporaryFile]](
    transform = { form: MultipartFormData[TemporaryFile] =>
    formatDataParts(form.dataParts) ++
      form.files.flatMap { file =>
        val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
        filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
      } ++
      Codec.utf_8.encode(s"--$boundary--")
  },
    contentType = Some(s"multipart/form-data; boundary=$boundary")
  )
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:49,代码来源:MultipartFormDataWritable.scala


示例18: CommonFilesService

//设置package包名称以及导入依赖的类
package com.pacbio.common.services

import java.nio.file.Paths

import akka.actor.ActorSystem
import com.pacbio.common.actors.ActorSystemProvider
import com.pacbio.common.dependency.Singleton
import com.pacbio.common.file.{FileSystemUtilProvider, FileSystemUtil}
import com.pacbio.common.models._

import scala.concurrent.ExecutionContext

// TODO(smcclellan): Add specs, docs
class CommonFilesService(mimeTypes: MimeTypes, fileSystemUtil: FileSystemUtil)(
    override implicit val actorSystem: ActorSystem,
    override implicit val ec: ExecutionContext)
  extends SimpleFilesService(mimeTypes, fileSystemUtil) with BaseSmrtService {

  override val serviceBaseId = "files"
  override val serviceName = "Common Files Service"
  override val serviceVersion = "0.1.1"
  override val serviceDescription = "Serves files from the root directory of the filesystem."

  // TODO(smcclellan): THIS IS SUPER-DUPER INSECURE
  override val rootDir = Paths.get("/")
}

trait CommonFilesServiceProvider {
  this: MimeTypeDetectors with FileSystemUtilProvider with ActorSystemProvider =>

  val commonFilesService: Singleton[CommonFilesService] = Singleton { () =>
    implicit val system = actorSystem()
    implicit val ec = scala.concurrent.ExecutionContext.global
    new CommonFilesService(mimeTypes(), fileSystemUtil())
  }.bindToSet(AllServices)
}

trait CommonFilesServiceProviderx {
  this: MimeTypeDetectors with FileSystemUtilProvider with ActorSystemProvider with ServiceComposer =>

  val commonFilesService: Singleton[CommonFilesService] = Singleton { () =>
    implicit val system = actorSystem()
    implicit val ec = scala.concurrent.ExecutionContext.global
    new CommonFilesService(mimeTypes(), fileSystemUtil())
  }

  addService(commonFilesService)
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:49,代码来源:CommonFilesService.scala


示例19: PacbioJsonProtocolSpec

//设置package包名称以及导入依赖的类
import java.nio.file.Paths

import com.pacbio.common.loaders.ManifestLoader
import com.pacbio.common.models._
import spray.json._
import org.specs2.mutable._
import org.joda.time.{DateTime => JodaDateTime}

class PacbioJsonProtocolSpec extends Specification {

  import PacBioJsonProtocol._

  "Serialize Alert Spec" should {
    "Alert serialize to Json " in {
      val m = Alarm("id", "name", "desc")
      m.name must beEqualTo("name")
      val x = m.toJson
      println(x)
      m.id must beEqualTo("id")
    }
    "Manifest serialization" in {
      val m = PacBioComponentManifest("myid", "myname", "0.1.1", "description")
      m.id must beEqualTo("myid")
      val x = m.toJson
      println(x)
      m.version must beEqualTo("0.1.1")
    }
    "Manifest serialization with Components" in {
      val m = PacBioComponentManifest("myid", "myname", "0.1.1", "description")
      m.id must beEqualTo("myid")
      val x = m.toJson
      println(x)
      m.version must beEqualTo("0.1.1")
    }
    "Load Example PacBio Manifest.json " in {

      val p = Paths.get(getClass.getResource("pacbio-manifest.json").toURI)

      val manifests = ManifestLoader.loadFrom(p.toFile)

      manifests.length should beEqualTo(2)
    }
  }
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:45,代码来源:PacbioJsonProtocolSpec.scala


示例20: SimpleDataTransferOptions

//设置package包名称以及导入依赖的类
package com.pacbio.secondary.analysis.jobtypes

import java.nio.file.{Files, Paths}

import com.pacbio.secondary.analysis.jobs._
import com.pacbio.secondary.analysis.jobs.JobModels._
import com.pacbio.secondary.analysis.jobs.JobModels.JobConstants.GENERAL_PROJECT_ID
import com.pacbio.secondary.analysis.tools.timeUtils
import org.apache.commons.io.FileUtils
import org.joda.time.{DateTime => JodaDateTime}

// DataTransfer
case class SimpleDataTransferOptions(src: String,
                                     dest: String,
                                     override val projectId: Int = GENERAL_PROJECT_ID) extends BaseJobOptions {
  def toJob = new SimpleDataTransferJob(this)
}



class SimpleDataTransferJob(opts: SimpleDataTransferOptions)
  extends BaseCoreJob(opts: SimpleDataTransferOptions)
  with timeUtils{

  type Out = ResultSuccess
  val jobTypeId = JobTypeId("simple_data_transfer")

  def run(job: JobResourceBase, resultsWriter: JobResultWriter): Either[ResultFailed, ResultSuccess] = {
    val startedAt = JodaDateTime.now()

    val srcP = Paths.get(opts.src)
    val destP = Paths.get(opts.dest)

    if (Files.isDirectory(srcP)) {
      logger.info(s"copying directory $srcP to $destP")
      FileUtils.copyDirectory(srcP.toFile, destP.toFile)
    } else {
      logger.info(s"copying file from $srcP to $destP")
      FileUtils.copyFile(srcP.toFile, destP.toFile)
    }
    //
    val msg = s"completed transferring files from: ${srcP.toString} to ${destP.toString}"
    logger.info(msg)

    val runTimeSec = computeTimeDeltaFromNow(startedAt)
    Right(ResultSuccess(job.jobId, jobTypeId.toString, "Completed running", runTimeSec, AnalysisJobStates.SUCCESSFUL, host))
  }


} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:51,代码来源:SimpleDataTransferJob.scala



注:本文中的java.nio.file.Paths类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ActorLogging类代码示例发布时间:2022-05-23
下一篇:
Scala JsValue类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap