java.util.function.Predicate Scala Examples

The following examples show how to use java.util.function.Predicate. 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: FileActorUtils.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.api.utils

import java.io.{BufferedOutputStream, File, FileOutputStream}
import java.net.InetAddress
import java.text.DecimalFormat
import java.util.function.Predicate

import akka.event.slf4j.SLF4JLogging
import com.stratio.sparta.serving.api.constants.HttpConstant
import com.stratio.sparta.serving.core.config.SpartaConfig
import com.stratio.sparta.serving.core.models.files.SpartaFile
import spray.http.BodyPart

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

trait FileActorUtils extends SLF4JLogging {

  //The dir where the files will be saved
  val targetDir: String
  val apiPath: String

  //Regexp for name validation
  val patternFileName: Option[Predicate[String]] = None

  def deleteFiles(): Try[_] =
    Try {
      val directory = new File(targetDir)
      if (directory.exists && directory.isDirectory)
        directory.listFiles.filter(_.isFile).toList.foreach { file =>
          if (patternFileName.isEmpty || (patternFileName.isDefined && patternFileName.get.test(file.getName)))
            file.delete()
        }
    }

  def deleteFile(fileName: String): Try[_] =
    Try {
      val plugin = new File(s"$targetDir/$fileName")
      if (plugin.exists && !plugin.isDirectory)
        plugin.delete()
    }

  def browseDirectory(): Try[Seq[SpartaFile]] =
    Try {
      val directory = new File(targetDir)
      if (directory.exists && directory.isDirectory) {
        directory.listFiles.filter(_.isFile).toList.flatMap { file =>
          if (patternFileName.isEmpty || (patternFileName.isDefined && patternFileName.get.test(file.getName)))
            Option(SpartaFile(file.getName, s"$url/${file.getName}", file.getAbsolutePath,
              sizeToMbFormat(file.length())))
          else None
        }
      } else Seq.empty[SpartaFile]
    }

  def uploadFiles(files: Seq[BodyPart]): Try[Seq[SpartaFile]] =
    Try {
      files.flatMap { file =>
        val fileNameOption = file.filename.orElse(file.name.orElse {
          log.warn(s"Is necessary one file name to upload files")
          None
        })
        fileNameOption.flatMap { fileName =>
          if (patternFileName.isEmpty || (patternFileName.isDefined && patternFileName.get.test(fileName))) {
            val localMachineDir = s"$targetDir/$fileName"

            Try(saveFile(file.entity.data.toByteArray, localMachineDir)) match {
              case Success(newFile) =>
                Option(SpartaFile(fileName, s"$url/$fileName", localMachineDir, sizeToMbFormat(newFile.length())))
              case Failure(e) =>
                log.error(s"Error saving file in path $localMachineDir", e)
                None
            }
          } else {
            log.warn(s"$fileName is Not a valid file name")
            None
          }
        }
      }
    }

  private def sizeToMbFormat(size: Long): String = {
    val formatter = new DecimalFormat("####.##")
    s"${formatter.format(size.toDouble / (1024 * 1024))} MB"
  }

  private def saveFile(array: Array[Byte], fileName: String): File = {
    log.info(s"Saving file to: $fileName")
    new File(fileName).getParentFile.mkdirs
    val bos = new BufferedOutputStream(new FileOutputStream(fileName))
    bos.write(array)
    bos.close()
    new File(fileName)
  }

  private def url: String = {
    val host = Try(InetAddress.getLocalHost.getHostName).getOrElse(SpartaConfig.apiConfig.get.getString("host"))
    val port = SpartaConfig.apiConfig.get.getInt("port")

    s"http://$host:$port/${HttpConstant.SpartaRootPath}/$apiPath"
  }
} 
Example 2
Source File: LocalStackReadyLogWaitStrategy.scala    From aws-spi-akka-http   with Apache License 2.0 5 votes vote down vote up
package com.github.matsluni.akkahttpspi.testcontainers

import java.util.concurrent.{TimeUnit, TimeoutException}
import java.util.function.Predicate

import org.testcontainers.DockerClientFactory
import org.testcontainers.containers.ContainerLaunchException
import org.testcontainers.containers.output.{OutputFrame, WaitingConsumer}
import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy
import org.testcontainers.utility.LogUtils

import scala.compat.java8.FunctionConverters._

object LocalStackReadyLogWaitStrategy extends AbstractWaitStrategy {
  override def waitUntilReady(): Unit = {
    val waitingConsumer = new WaitingConsumer
    LogUtils.followOutput(DockerClientFactory.instance.client, waitStrategyTarget.getContainerId, waitingConsumer)

    val waitPredicate: Predicate[OutputFrame] = ((outputFrame: OutputFrame) => outputFrame.getUtf8String.contains("Ready.")).asJava

    try
      waitingConsumer.waitUntil(waitPredicate, startupTimeout.getSeconds, TimeUnit.SECONDS, 1)
    catch {
      case e: TimeoutException =>
        throw new ContainerLaunchException("Timed out waiting for localstack")
    }
  }
} 
Example 3
Source File: VersionBuffer.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.util

import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Predicate

import scala.collection.mutable.ListBuffer

class VersionBuffer[T] {

  private val buffer = new ConcurrentLinkedDeque[(Int, T)]()

  def add(version: Int, value: T): Unit = synchronized {
    if (buffer.isEmpty) {
      buffer.addLast((version, value))
    } else {
      buffer.getLast match {
        case (ver, _) =>
          require(ver < version || version == 0, "Cannot add version older than newest version")
          buffer.addLast((version, value))
      }
    }
  }

  def oldestVersion: Option[Int] = Option(buffer.getFirst).map(_._1)
  def newestVersion: Option[Int] = Option(buffer.getLast).map(_._1)

  def discardUntil(version: Int): Unit = synchronized {
    buffer.removeIf {
      new Predicate[(Int, T)] {
        def test(t: (Int, T)): Boolean = t._1 < version
      }
    }
  }

  def getRange(startVersion: Int, endVersion: Int): List[T] = getRangeV(startVersion, endVersion).map(_._2)

  def getRangeV(startVersion: Int, endVersion: Int): List[(Int, T)] = {
    val iter = buffer.iterator()
    val results = new ListBuffer[(Int, T)]
    var finished = false

    if (startVersion > endVersion) {
      // there's a wraparound between start and end
      var lastVersion = 0
      while (!finished && iter.hasNext) {
        val (version, value) = iter.next()
        if (version < lastVersion)
          finished = true
        results += (version -> value)
      }
      finished = false
    }

    while (!finished && iter.hasNext) {
      val (version, value) = iter.next()
      if (version > endVersion) {
        finished = true
      } else {
        results += (version -> value)
      }
    }
    results.toList
  }

} 
Example 4
Source File: LinePattern.scala    From MoVE   with Mozilla Public License 2.0 5 votes vote down vote up
package de.thm.move.models

import java.util.function.Predicate
import javafx.scene.Node

object LinePattern extends Enumeration {
  type LinePattern = Value
  val None, Solid, Dash, Dot, DashDot, DashDotDot = Value

  val linePatternToCssClass: Map[LinePattern.LinePattern, String] =
    Map(
      LinePattern.None -> "none-stroke",
      LinePattern.Solid -> "solid-stroke",
      LinePattern.Dash -> "dash-stroke",
      LinePattern.Dot -> "dotted-stroke",
      LinePattern.DashDot -> "dash-dotted-stroke",
      LinePattern.DashDotDot -> "dash-dotted-dotted-stroke"
    )

  val cssRegex = ".*-stroke"

  //remove old stroke style
  val removeOldCss: (Node) => Unit = { shape =>
    shape.getStyleClass().removeIf(new Predicate[String]() {
      override def test(str:String): Boolean = str.`matches`(cssRegex)
    })
  }
} 
Example 5
Source File: PluginXmlDetector.scala    From sbt-idea-plugin   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.sbtidea.download

import java.net.URI
import java.nio.file.{FileSystems, Files, Path}
import java.util.Collections
import java.util.function.Predicate

private class PluginXmlDetector extends Predicate[Path] {

  import org.jetbrains.sbtidea.packaging.artifact._

  private val MAP = Collections.emptyMap[String, Any]()
  var result: String = _

  override def test(t: Path): Boolean = {
    if (!t.toString.endsWith(".jar"))
      return false

    val uri = URI.create(s"jar:${t.toUri}")

    try {
      using(FileSystems.newFileSystem(uri, MAP)) { fs =>
        val maybePluginXml = fs.getPath("META-INF", "plugin.xml")
        if (Files.exists(maybePluginXml)) {
          result = new String(Files.readAllBytes(maybePluginXml))
          true
        } else {
          false
        }
      }
    } catch {
      case e: java.util.zip.ZipError => throw new RuntimeException(s"Corrupt zip file: $t", e)
    }
  }
} 
Example 6
Source File: BuildIndex.scala    From sbt-idea-plugin   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.sbtidea.searchableoptions

import java.nio.file.{Files, Path}
import java.util.function.Predicate

import org.jetbrains.sbtidea.Keys.{intellijMainJars, intellijVMOptions}
import org.jetbrains.sbtidea.packaging.PackagingKeys.packageArtifact
import org.jetbrains.sbtidea.packaging._
import org.jetbrains.sbtidea.packaging.artifact.DistBuilder
import org.jetbrains.sbtidea.runIdea.IdeaRunner
import org.jetbrains.sbtidea.{pathToPathExt, PluginLogger, SbtPluginLogger}
import sbt.Keys.{streams, target}
import sbt._

import scala.collection.JavaConverters._

object BuildIndex {

  private val IDX_DIR = "search"
  type IndexElement = (Path, Path) // jar file -> options.xml

  def createTask: Def.Initialize[Task[Unit]] = Def.task {
    implicit val log: PluginLogger = new SbtPluginLogger(streams.value)

    val ideaCP          = intellijMainJars.value.map(_.data.toPath)
    val pluginRoot      = packageArtifact.value.toPath
    val indexOutputPath = target.value / "searchableOptions"
    val indexerCMD      = "traverseUI" :: indexOutputPath.getCanonicalPath :: "true" :: Nil
    val vmOptions       = intellijVMOptions.value

    log.info("Building searchable plugin options index...")
    val runner = new IdeaRunner(ideaCP, vmOptions, blocking = true, programArguments = indexerCMD)
    runner.run()

    val indexRoots          = getIndexFiles(pluginRoot, indexOutputPath.toPath)
    val indexedMappings     = prepareMappings(indexRoots)

    if (indexRoots.isEmpty)
      log.error(s"No options search index built for plugin root: $pluginRoot")

    if (indexedMappings.isEmpty)
      log.error(s"No options search index packaged from given roots: $indexRoots")

    indexedMappings.foreach { case (jar, mapping) =>
      new DistBuilder(streams.value, target.value).patch(jar, Seq(mapping))
    }

    log.info(s"Successfully merged options index")
  }


  private def getIndexFiles(pluginOutputDir: Path, indexOutputDir: Path): Seq[IndexElement] = {
    val predicate = new Predicate[Path] { override def test(p: Path): Boolean = p.toString.endsWith("jar") }

    val allArtifactJars = Files.walk(pluginOutputDir)
      .filter(predicate)
      .iterator().asScala
      .map(path => path.getFileName.toString -> path)
      .toMap

    val indexesForPlugin: Seq[(Path, Path)] = indexOutputDir
      .list
      .filter(idx => allArtifactJars.contains(idx.getFileName.toString))
      .filter(idx => (idx / IDX_DIR).exists && (idx / IDX_DIR).isDir && (idx / IDX_DIR).list.nonEmpty)
      .foldLeft(Seq.empty[IndexElement]) { (acc, idx) =>
        acc :+ (allArtifactJars(idx.getFileName.toString) -> (idx / IDX_DIR).list.head)
      }

    indexesForPlugin
  }

  private def prepareMappings(indexes: Seq[IndexElement]): Seq[(Path, Mapping)] =
    indexes.map { case (jar, indexXML) =>
      jar ->
        Mapping(indexXML.toFile,
          new File( s"$jar!/search/searchableOptions.xml"),
          MappingMetaData.EMPTY.copy(kind = MAPPING_KIND.MISC))
    }



}