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

Scala Optional类代码示例

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

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



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

示例1: create

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.sse
package javadsl

import akka.NotUsed
import akka.http.javadsl.model.{HttpRequest, HttpResponse, Uri}
import akka.http.scaladsl.model.{HttpResponse => SHttpResponse}
import akka.stream.Materializer
import akka.stream.javadsl.Source
import akka.http.javadsl.model.sse.ServerSentEvent
import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{Function => JFunction}
import scala.compat.java8.FutureConverters
import scala.compat.java8.OptionConverters


  def create(uri: Uri,
             send: JFunction[HttpRequest, CompletionStage[HttpResponse]],
             lastEventId: Optional[String],
             mat: Materializer): Source[ServerSentEvent, NotUsed] = {
    val eventSource =
      scaladsl.EventSource(
        uri.asInstanceOf[akka.http.impl.model.JavaUri].uri,
        send(_).toScala.map(_.asInstanceOf[SHttpResponse])(mat.executionContext),
        lastEventId.asScala
      )(mat)
    eventSource.asJava
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:30,代码来源:EventSource.scala


示例2: MicroserviceExceptionSerializer

//设置package包名称以及导入依赖的类
package io.scalac.lagom.utils

import java.util.Optional
import java.util.concurrent.CompletionException

import akka.util.ByteString
import com.lightbend.lagom.javadsl.api.deser.{ExceptionSerializer, RawExceptionMessage}
import com.lightbend.lagom.javadsl.api.transport.{MessageProtocol, TransportErrorCode}

class MicroserviceExceptionSerializer extends ExceptionSerializer {
  override def serialize(exception: Throwable, accept: java.util.Collection[MessageProtocol]): RawExceptionMessage = {
    val mp = MessageProtocol.fromContentTypeHeader(Optional.empty())

    def defaultMessage = new RawExceptionMessage(
      TransportErrorCode.InternalServerError,
      mp,
      ByteString.apply(exception.getMessage)
    )

    def getMessageForCompletionException(completionEx: CompletionException) =
      completionEx.getCause match {
        case ex: ServerError =>
          new RawExceptionMessage(
            TransportErrorCode.InternalServerError,
            mp,
            ByteString.apply(ex.msg)
          )
        case ex => defaultMessage
      }

    exception match {
      case ex: CompletionException =>
        getMessageForCompletionException(ex)
      case ex: Throwable =>
        defaultMessage
    }
  }

  //let's leave it unimplemented since it's not required for our example to work
  override def deserialize(message: RawExceptionMessage): Throwable = ???
} 
开发者ID:ScalaConsultants,项目名称:lagom-scala-post-example,代码行数:42,代码来源:MicroserviceExceptionSerializer.scala


示例3: CorsSettings

//设置package包名称以及导入依赖的类
package ch.megard.akka.http.cors.javadsl.settings

import java.util.Optional

import akka.http.javadsl.model.HttpMethod
import akka.http.javadsl.model.headers.HttpOriginRange
import ch.megard.akka.http.cors.javadsl.model.HttpHeaderRange
import ch.megard.akka.http.cors.scaladsl


abstract class CorsSettings {

  def getAllowGenericHttpRequests: Boolean
  def getAllowCredentials: Boolean
  def getAllowedOrigins: HttpOriginRange
  def getAllowedHeaders: HttpHeaderRange
  def getAllowedMethods: java.lang.Iterable[HttpMethod]
  def getExposedHeaders: java.lang.Iterable[String]
  def getMaxAge: Optional[Long]

  def withAllowGenericHttpRequests(newValue: Boolean): CorsSettings
  def withAllowCredentials(newValue: Boolean): CorsSettings
  def withAllowedOrigins(newValue: HttpOriginRange): CorsSettings
  def withAllowedHeaders(newValue: HttpHeaderRange): CorsSettings
  def withAllowedMethods(newValue: java.lang.Iterable[HttpMethod]): CorsSettings
  def withExposedHeaders(newValue: java.lang.Iterable[String]): CorsSettings
  def withMaxAge(newValue: Optional[Long]): CorsSettings

}

object CorsSettings {

  def defaultSettings: CorsSettings = scaladsl.settings.CorsSettings.defaultSettings

} 
开发者ID:lomigmegard,项目名称:akka-http-cors,代码行数:36,代码来源:CorsSettings.scala


示例4: TestUserManagementRepository

//设置package包名称以及导入依赖的类
package io.skysail.um.repo.test

import io.skysail.api.um.UserManagementRepository
import org.osgi.service.component.annotations.Component
import java.util.Optional
import org.restlet.security.User
import org.restlet.security.Role
import org.slf4j.LoggerFactory
import scala.collection.JavaConverters._

@Component(immediate = true)
class TestUserManagementRepository extends UserManagementRepository {

  private var log = LoggerFactory.getLogger(this.getClass())

  val users = scala.collection.mutable.Map[String, User]()
  def getUsers() = users.asJava

  val roles = scala.collection.mutable.Set[Role]()
  def getRoles() = roles.asJava

  val usersRoles = scala.collection.mutable.Map[User, java.util.Set[Role]]()
  def getUsersRoles = usersRoles.asJava

  def getUser(username: String): Optional[User] = {
    if (users.get(username).isEmpty) {
      log.warn("running fixed UserManagement Repository, i.e. creating dummy user for username '{}'", username)
      users += username -> new User(username, username.toCharArray(), "firstname", "lastname", "[email protected]")
      var fixedRoles = new java.util.HashSet[Role]()

      val userRole = new Role("user")
      val roleNamedLikeUsername = new Role(username)

      roles.add(userRole)
      roles.add(roleNamedLikeUsername)

      fixedRoles.add(userRole)
      fixedRoles.add(roleNamedLikeUsername)

      usersRoles.put(users.get(username).get, fixedRoles)
    }
    Optional.of(users.get(username).get)
  }

} 
开发者ID:evandor,项目名称:skysail-um,代码行数:46,代码来源:TestUserManagementRepository.scala


示例5: JBasicLoggerActor

//设置package包名称以及导入依赖的类
package csw.services.logging.javadsl
import java.util.Optional

import akka.actor.{AbstractActor, ActorPath}
import akka.serialization.Serialization
import akka.typed.javadsl.ActorContext
import csw.services.logging.internal.JLogger
import csw.services.logging.scaladsl.LoggerImpl

import scala.compat.java8.OptionConverters.RichOptionalGeneric


abstract class JBasicLoggerActor extends AbstractActor {
  protected def maybeComponentName: Optional[String]
  protected def getLogger: ILogger = {
    val actorName = ActorPath.fromString(Serialization.serializedActorPath(getSelf)).toString
    val log       = new LoggerImpl(maybeComponentName.asScala, Some(actorName))
    new JLogger(log, getClass)
  }
}

import akka.typed.scaladsl.adapter._
abstract class JBasicLoggerTypedActor[T](actorContext: ActorContext[T])
    extends akka.typed.javadsl.Actor.MutableBehavior[T] {
  protected def maybeComponentName: Optional[String]
  protected def getLogger: ILogger = {
    val actorName = ActorPath.fromString(Serialization.serializedActorPath(actorContext.getSelf.toUntyped)).toString
    val log       = new LoggerImpl(maybeComponentName.asScala, Some(actorName))
    new JLogger(log, getClass)
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:32,代码来源:loggers.scala


示例6: DocumentEntity

//设置package包名称以及导入依赖的类
package com.iservport.doc.impl

import java.util.{Date, Optional}

import akka.Done
import com.iservport.doc.api.{Document, Voter}
import com.lightbend.lagom.javadsl.persistence.PersistentEntity

class DocumentEntity extends PersistentEntity[DocumentCommand, DocumentEvent, DocumentState] {

  import scala.collection.JavaConverters._
  import scala.compat.java8.OptionConverters._

  override def initialBehavior(snapshotState: Optional[DocumentState]): Behavior = {

    val b = newBehaviorBuilder(snapshotState.orElseGet(() => DocumentState(Option.empty)))

    b.setCommandHandler(classOf[CreateDocument], (cmd: CreateDocument, ctx: CommandContext[Done]) => {
      state.document match {
        case Some(_) =>
          ctx.invalidCommand(s"Document ${entityId} is already created")
          ctx.done()
        case None =>
          // Do persist event
          val d = cmd.document
          val events = DocumentCreated(d.id, d.entityId, d.docCode, d.docName, d.docAbstract, d.issueDate, d.authorId,
            d.authorName, d.docType, d.docContent) +:
            d.voters.map(vote => VoteAdded(d.id, vote.voterId, vote.voterName, vote.voted))
          ctx.thenPersistAll(events.asJava, () => ctx.reply(Done))
      }
    })

    b.setEventHandler(classOf[DocumentCreated], (evt: DocumentCreated) => DocumentState(
      new Document(evt.id, evt.entityId, evt.docCode, evt.docName, evt.docAbstract, evt.issueDate, evt.authorId,
        evt.authorName, evt.docType, evt.docContent))
    )

    b.setCommandHandler(classOf[AddVote], (cmd: AddVote, ctx: CommandContext[Done]) => {
      state.document match {
        case None =>
          ctx.invalidCommand(s"Document ${entityId} is not  created")
          ctx.done()
        case Some(d) =>
          ctx.thenPersist(VoteAdded(d.id, cmd.voterId, cmd.voterName, cmd.voted), (evt: VoteAdded) => ctx.reply(Done))
      }
    })

    b.setEventHandler(classOf[VoteAdded], (evt: VoteAdded) => state.vote(Voter(evt.voterId, evt.voterName, evt.voted)))

    b.setReadOnlyCommandHandler(classOf[GetDocument], (cmd: GetDocument, ctx: ReadOnlyCommandContext[GetDocumentReply]) =>
      ctx.reply(GetDocumentReply(state.document))
    )

    b.build()

  }

} 
开发者ID:iservport,项目名称:iservport-voter,代码行数:59,代码来源:DocumentEntity.scala


示例7: SbtTypes

//设置package包名称以及导入依赖的类
package org.romanowski.hoarder.core

import sbt.Artifact
import sbt.File
import sbt.IO.transfer
import java.net.URL
import java.nio.file.Paths
import java.util.Optional

import sbt.io.Using
import xsbti.compile._
import sbt.librarymanagement.ConfigRef


object SbtTypes {
  type CompilationResult = xsbti.compile.CompileResult
  type PreviousCompilationResult = xsbti.compile.PreviousResult

  implicit class IOOps(io: sbt.io.IO.type){
    def download(url: URL, to: File) =
      Using.urlInputStream(url) { inputStream =>
        transfer(inputStream, to)
      }
  }

  def createArtifact(name: String,
                    `type`: String,
                    extension: String,
                    classifier: Option[String],
                    configurations: Seq[sbt.Configuration]): Artifact =
    Artifact(name, `type`, extension, classifier, configurations.map(n => ConfigRef(n.name)).toVector, None)

  def fail(m: String) = throw new RuntimeException(m)

  implicit class CompilationResultOps(results: CompilationResult){
    def asAnalysisContents: AnalysisContents = AnalysisContents.create(results.analysis(), results.setup())


    def compiledAfter(date: Long): Set[String] ={
      results.analysis() match {
        case analysis: sbt.internal.inc.Analysis =>
          val relations = analysis.relations
          analysis.apis.internal.collect {
            case (file, source) if source.compilationTimestamp() > date =>
              relations.definesClass(file).map(_.getName())
          }.flatten.toSet
      }
    }
  }

  implicit class AnalysisContentsOps(content: AnalysisContents){
    def asPreviousResults: PreviousCompilationResult =
      PreviousResult.create(Optional.of(content.getAnalysis()), Optional.of(content.getMiniSetup()))
  }

} 
开发者ID:romanowski,项目名称:hoarder,代码行数:57,代码来源:SbtTypes.scala


示例8: SocketIOSessionFlowHelper

//设置package包名称以及导入依赖的类
package play.socketio.javadsl

import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ BiFunction, Function }

import akka.NotUsed
import akka.stream.Materializer
import akka.stream.javadsl.Flow
import com.fasterxml.jackson.databind.JsonNode
import play.api.libs.json.Json
import play.mvc.Http.RequestHeader
import play.socketio.{ SocketIOConfig, SocketIOEvent, SocketIOSession, SocketIOSessionFlow }

import scala.concurrent.ExecutionContext
import scala.Function.unlift
import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters._


private[javadsl] object SocketIOSessionFlowHelper {

  def createEngineIOSessionHandler[SessionData](
    config:                     SocketIOConfig,
    connectCallback:            BiFunction[RequestHeader, String, CompletionStage[SessionData]],
    errorHandler:               Function[Throwable, Optional[JsonNode]],
    defaultNamespaceCallback:   Function[SocketIOSession[SessionData], Flow[SocketIOEvent, SocketIOEvent, NotUsed]],
    connectToNamespaceCallback: BiFunction[SocketIOSession[SessionData], String, Optional[Flow[SocketIOEvent, SocketIOEvent, NotUsed]]]
  )(implicit ec: ExecutionContext, mat: Materializer) = {
    SocketIOSessionFlow.createEngineIOSessionHandler[SessionData](
      config,
      (request, sid) => connectCallback(request.asJava, sid).toScala,
      unlift(t => errorHandler(t).asScala.map(Json.toJson(_))),
      session => defaultNamespaceCallback(session).asScala,
      unlift {
        case (session, sid) => connectToNamespaceCallback(session, sid).asScala.map(_.asScala)
      }
    )
  }
} 
开发者ID:playframework,项目名称:play-socket.io,代码行数:41,代码来源:SocketIOSessionFlowHelper.scala


示例9: BasicAuthenticator

//设置package包名称以及导入依赖的类
package pl.scalare.main

import java.util.Optional

import io.dropwizard.auth.Authenticator
import io.dropwizard.auth.basic.BasicCredentials
import pl.scalare.rest.User

class BasicAuthenticator extends Authenticator[BasicCredentials, User] {
  override def authenticate(credentials: BasicCredentials): Optional[User] = {
    val bool = "password".equals(credentials.getPassword())
    val user = if (bool) new User(credentials.getUsername()) else null
    return Optional.ofNullable(user)
  }
}

class OAuthAuthenticator extends Authenticator[String, User] {
  override def authenticate(token: String): Optional[User] = {
    val bool = "password".equals(token)
    val user = if (bool) new User("") else null
    return Optional.ofNullable(user)
  }
} 
开发者ID:writeonly,项目名称:scalare,代码行数:24,代码来源:ScalareAuthenticator.scala


示例10: TestServiceLocator

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.testkit

import java.net.URI
import java.util.Optional
import java.util.concurrent.CompletionStage

import scala.compat.java8.FutureConverters._
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import com.lightbend.lagom.javadsl.api.Descriptor
import javax.inject.Inject
import javax.inject.Singleton

import com.lightbend.lagom.javadsl.client.{ CircuitBreakersPanel, CircuitBreakingServiceLocator }

@Singleton
private[lagom] class TestServiceLocator @Inject() (
  circuitBreakers: CircuitBreakersPanel,
  port:            TestServiceLocatorPort,
  implicit val ec: ExecutionContext
) extends CircuitBreakingServiceLocator(circuitBreakers) {

  private val futureUri = port.port.map(p => URI.create("http://localhost:" + p))

  override def locate(name: String, call: Descriptor.Call[_, _]): CompletionStage[Optional[URI]] =
    futureUri.map(uri => Optional.of(uri)).toJava
}

private[lagom] final case class TestServiceLocatorPort(port: Future[Int]) 
开发者ID:lagom,项目名称:lagom,代码行数:30,代码来源:TestServiceLocator.scala


示例11: PersistentEntityTestDriverCompatSpec

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.javadsl.testkit

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import com.lightbend.lagom.javadsl.persistence.TestEntity
import akka.testkit.TestProbe
import com.lightbend.lagom.internal.javadsl.persistence.PersistentEntityActor
import java.util.Optional

import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraPersistenceSpec

class PersistentEntityTestDriverCompatSpec extends CassandraPersistenceSpec {

  "PersistentEntityActor and PersistentEntityTestDriver" must {
    "produce same events and state" in {
      val probe1 = TestProbe()
      val p = system.actorOf(PersistentEntityActor.props("test", Optional.of("1"),
        () => new TestEntity(system, probe1.ref), Optional.empty(), 10.seconds))
      val probe2 = TestProbe()
      val driver = new PersistentEntityTestDriver(system, new TestEntity(system, probe2.ref), "1")

      val commands = List(
        TestEntity.Get.instance,
        TestEntity.Add.of("a"),
        TestEntity.Add.of("b"),
        TestEntity.Add.of(""),
        new TestEntity.ChangeMode(TestEntity.Mode.PREPEND),
        TestEntity.Add.of("C"),
        new TestEntity.Add("D", 2),
        TestEntity.Get.instance
      )

      val outcome = driver.run(commands: _*)

      commands.foreach(p ! _)

      val replySideEffects = outcome.sideEffects.asScala.collect {
        case PersistentEntityTestDriver.Reply(msg) => msg
      }
      val replies = receiveN(replySideEffects.size)
      replySideEffects should be(replies)
      // Add 2 generates 2 events, but only one reply so drop last event when comparing
      outcome.events.asScala.dropRight(1) should be(replies.collect { case evt: TestEntity.Evt => evt })

      outcome.state should be(replies.last)

      expectNoMsg(200.millis)
      probe1.expectMsgType[TestEntity.AfterRecovery]
      probe2.expectMsgType[TestEntity.AfterRecovery]

      outcome.issues.asScala.toList should be(Nil)
    }

  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:57,代码来源:PersistentEntityTestDriverCompatSpec.scala


示例12: serialize

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.javadsl.api

import java.lang.reflect.{ ParameterizedType, Type }
import java.util.Optional

import com.lightbend.lagom.javadsl.api.deser.{ PathParamSerializer, PathParamSerializers }
import org.pcollections.{ PSequence, TreePVector }

import scala.compat.java8.FunctionConverters._

trait UnresolvedPathParamSerializer[Param] extends PathParamSerializer[Param] {
  def serialize(parameter: Param) = throw new NotImplementedError("Cannot use unresolved path param serializer to serialize path params")

  def deserialize(parameters: PSequence[String]) = throw new NotImplementedError("Cannot use unresolved path param serializer to deserialize path params")

  def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Param]
}

class UnresolvedTypePathParamSerializer[Param] extends UnresolvedPathParamSerializer[Param] {
  override def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Param] = {
    resolver.pathParamSerializerFor(typeInfo, typeInfo)
  }
}

class UnresolvedOptionalPathParamSerializer[Param] extends UnresolvedPathParamSerializer[Optional[Param]] {
  override def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Optional[Param]] = {
    typeInfo match {
      case paramType: ParameterizedType if paramType.getRawType == classOf[Optional[_]] =>
        val wrappedType = paramType.getActualTypeArguments.apply(0)
        val subTypeSerializer = resolver.pathParamSerializerFor[Param](wrappedType, wrappedType)
        PathParamSerializers.optional[Param](
          wrappedType.getTypeName,
          (subTypeSerializer.deserialize _).compose((p: String) => TreePVector.singleton(p)).asJava,
          (subTypeSerializer.serialize _).andThen {
          case single if single.size() == 1 => single.get(0)
          case other                        => throw new IllegalStateException("Can only wrap an Optional serializer around a path param serializer that produces exactly one parameter")
        }.asJava
        )
      case _ => throw new IllegalArgumentException("Unresolved optional path param serializer can only be resolved against ParamaterizedType descriptors for the Optional class. This serializer was resolved against: " + typeInfo)
    }
  }
} 
开发者ID:lagom,项目名称:lagom,代码行数:43,代码来源:PathParamSerializers.scala


示例13: JCompatCommand

//设置package包名称以及导入依赖的类
package com.nthportal.shell
package compat

import java.util
import java.util.Optional

import com.nthportal.shell.compat.Converters._
import com.nthportal.shell.compat.{Command => JCommand}
import com.nthportal.shell.{Command => SCommand}

import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._

private[compat] case class JCompatCommand(command: SCommand) extends JCommand {
  override def name(): String = command.name

  override def description(): Optional[String] = toJava(command.description)

  override def help(args: util.List[String]): Optional[String] = toJava(command.help(listToScalaImmutableSeq(args)))

  override def tabComplete(args: util.List[String]): util.List[String] = {
    seqAsJavaList(command.tabComplete(listToScalaImmutableSeq(args)))
  }

  override def execute(args: util.List[String], sink: OutputSink): Unit = {
    command.execute(listToScalaImmutableSeq(args))(sink)
  }
} 
开发者ID:NthPortal,项目名称:app-shell,代码行数:29,代码来源:JCompatCommand.scala


示例14: DefaultCommandTest

//设置package包名称以及导入依赖的类
package com.nthportal.shell.compat

import java.util
import java.util.{Collections, Optional}

import com.nthportal.shell.{OutputSink, SimpleSpec}

class DefaultCommandTest extends SimpleSpec {
  behavior of s"Default ${classOf[Command].getSimpleName} (Java)"

  it should "return an empty `Optional` for `description` and `help` methods" in {
    val c = new Command {
      override val name: String = "something"

      override def execute(args: util.List[String], sink: OutputSink): Unit = {}
    }

    c.description shouldEqual Optional.empty()
    c.help(Collections.emptyList()) shouldEqual Optional.empty()
    c.help(util.Arrays.asList(c.name)) shouldEqual Optional.empty()
    c.help(util.Arrays.asList("a", "list", "of", "sorts")) shouldEqual Optional.empty()
    c.tabComplete(util.Arrays.asList("a", "list", "of", "sorts")) shouldBe empty
  }
} 
开发者ID:NthPortal,项目名称:app-shell,代码行数:25,代码来源:DefaultCommandTest.scala


示例15: OptionalTypeAdapterFactory

//设置package包名称以及导入依赖的类
package cz.augi.gsonscala

import java.lang.reflect.ParameterizedType
import java.util.Optional

import com.google.gson.reflect.TypeToken
import com.google.gson.stream.{JsonReader, JsonWriter}
import com.google.gson.{Gson, TypeAdapter, TypeAdapterFactory}

object OptionalTypeAdapterFactory extends TypeAdapterFactory {
  override def create[T](gson: Gson, t: TypeToken[T]): TypeAdapter[T] =
    if (classOf[Optional[_]].isAssignableFrom(t.getRawType)) new OptionalTypeAdapter(gson, t) else null
}

class OptionalTypeAdapter[T](gson: Gson, t: TypeToken[T]) extends TypeAdapter[T] {
  val innerType = t.getType.asInstanceOf[ParameterizedType].getActualTypeArguments()(0)

  override def write(out: JsonWriter, value: T): Unit =
    value match {
      case o: Optional[_] =>
        if (o.isPresent) {
          gson.toJson(o.get, innerType, out)
        } else {
          // we must forcibly write null in order the read method to be called
          val orig = out.getSerializeNulls
          out.setSerializeNulls(true)
          out.nullValue()
          out.setSerializeNulls(orig)
        }
    }

  override def read(in: JsonReader): T = Optional.ofNullable(gson.fromJson(in, innerType)).asInstanceOf[T]
} 
开发者ID:augi,项目名称:gson-scala,代码行数:34,代码来源:OptionalTypeAdapter.scala


示例16: NonNullTypeAdapterFactory

//设置package包名称以及导入依赖的类
package cz.augi.gsonscala

import java.util.Optional

import com.google.gson.reflect.TypeToken
import com.google.gson.stream.{JsonReader, JsonWriter}
import com.google.gson.{Gson, TypeAdapter, TypeAdapterFactory}

object NonNullTypeAdapterFactory extends TypeAdapterFactory {
  override def create[T](gson: Gson, t: TypeToken[T]): TypeAdapter[T] = {
    if (t.getRawType.isPrimitive) {
      null
    } else {
      val adapter = new NonNullTypeAdapter[T](t.getRawType, gson.getDelegateAdapter(this, t))
      if (adapter.fields.nonEmpty) adapter else null
    }
  }

  def getDefaultValue(t: Class[_]): Any =
    if (classOf[Option[_]].isAssignableFrom(t)) Option.empty
    else if (classOf[Optional[_]].isAssignableFrom(t)) Optional.empty()
    else if (classOf[Seq[_]].isAssignableFrom(t)) Seq.empty
    else null

  class NonNullTypeAdapter[T](c: Class[_ >: T], delegate: TypeAdapter[T]) extends TypeAdapter[T] {
    val fields = c.getDeclaredFields
                  .map(f => (f, getDefaultValue(f.getType)))
                  .filter(_._2 != null)
    fields.foreach { case (f, _) => if (!f.isAccessible) f.setAccessible(true) }

    override def write(out: JsonWriter, value: T): Unit = delegate.write(out, value)

    override def read(in: JsonReader): T = {
      val r = delegate.read(in)
      fields.foreach { case (f, dv) => if (f.get(r) == null) f.set(r, dv) }
      r
    }
  }
} 
开发者ID:augi,项目名称:gson-scala,代码行数:40,代码来源:NonNullTypeAdapterFactory.scala


示例17: FjToScalaOptionConversion

//设置package包名称以及导入依赖的类
package ch.acmesoftware.fjscalaconversions

import java.util.Optional

private[fjscalaconversions] trait OptionConverter {
  implicit class FjToScalaOptionConversion[T](opt: fj.data.Option[T]) {
    def asScala(): Option[T] = if (opt.isSome) Some(opt.some()) else None
  }

  implicit class Java8ToScalaOptionConversion[T](opt: Optional[T]) {
    def asScala(): Option[T] = if (opt.isPresent) Some(opt.get()) else None
  }

  implicit class ScalaToFjOptionConversion[T](opt: Option[T]) {
    def asFj(): fj.data.Option[T] = opt.map(v => fj.data.Option.some(v)).getOrElse(fj.data.Option.none())
    def asJava8(): Optional[T] = opt.map(v => Optional.of(v)).getOrElse(Optional.empty())
  }
} 
开发者ID:acme-software,项目名称:fj-scala-conversions,代码行数:19,代码来源:OptionConverter.scala


示例18: Java8OptionalSpec

//设置package包名称以及导入依赖的类
package ch.acmesoftware.fjscalaconversions

import java.util.Optional

import org.scalatest._

class Java8OptionalSpec extends WordSpec with MustMatchers {

  "Option conversion" when {

    "applied to java.util.Optional[T]" should {

      val testData = Seq(
        (Optional.of("test"), Some("test")),
        (Optional.empty(), None),
        (Optional.ofNullable(null), None),
        (Optional.ofNullable("test"), Some("test"))
      )

      for (dataset <- testData.zipWithIndex) {
        s"""${dataset._2}: convert ${dataset._1._1.getClass.toString} to ${dataset._1._2}""" in {
          dataset._1._1.asScala() mustEqual dataset._1._2
        }
      }
    }

    "applied to scala.Option[T]" should {

      val testData = Seq(
        (Optional.of("test"), Some("test")),
        (Optional.empty(), None),
        (Optional.ofNullable(null), None),
        (Optional.ofNullable("test"), Some("test"))
      )

      for (dataset <- testData.zipWithIndex) {
        s"""${dataset._2}: convert  ${dataset._1._2} to ${dataset._1._1.getClass.toString}""" in {
          dataset._1._2.asJava8() mustEqual dataset._1._1
        }
      }
    }
  }
} 
开发者ID:acme-software,项目名称:fj-scala-conversions,代码行数:44,代码来源:Java8OptionalSpec.scala


示例19: ZipUtils

//设置package包名称以及导入依赖的类
package com.socialthingy.plusf.wos

import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
import java.util.{Collections, Optional}
import java.util.zip.{ZipEntry, ZipFile}

import scala.collection.mutable.ListBuffer
import scala.util.Try
import scala.util.control.NonFatal
import scala.collection.JavaConverters._

object ZipUtils {
  def isZipFile(file: File): Boolean = {
    val isZip = Try {
      val zf = new ZipFile(file)
      zf.close()
    }

    isZip.isSuccess
  }

  def findFiles(file: File): java.util.List[ZipEntry] = withZipFile(file)(Collections.emptyList[ZipEntry]()) { zf =>
    val entriesInFile = zf.entries()
    val matchingEntries = ListBuffer[ZipEntry]()
    while (entriesInFile.hasMoreElements) {
      val next = entriesInFile.nextElement
      val name = next.getName.toLowerCase()
      if (name.endsWith(".tap") || name.endsWith(".tzx")) {
        matchingEntries.append(next)
      }
    }
    matchingEntries.asJava
  }

  def unzipFile(zipFile: File, entry: ZipEntry): Optional[File] = withZipFile(zipFile)(Optional.empty[File]) { zf =>
    val unzipped = File.createTempFile("plusf", entry.getName)
    unzipped.deleteOnExit()
    val stream = zf.getInputStream(entry)
    try {
      Files.copy(stream, unzipped.toPath, REPLACE_EXISTING)
      Optional.of(unzipped)
    } finally {
      stream.close()
    }
  }

  private def withZipFile[T](file: File)(onError: => T)(fn: ZipFile => T): T = try {
    val zf = new ZipFile(file)
    try {
      fn(zf)
    } finally {
      zf.close()
    }
  } catch {
    case NonFatal(e) => onError
  }
} 
开发者ID:alangibson27,项目名称:plus-f,代码行数:60,代码来源:ZipUtils.scala


示例20: DnsServiceLocator

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.dns

import java.net.URI
import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ Function => JFunction }
import javax.inject.{ Inject, Named }

import akka.actor.{ ActorRef, ActorSystem }
import akka.pattern.ask
import com.lightbend.lagom.javadsl.api.{ Descriptor, ServiceLocator }
import com.lightbend.dns.locator.{ Settings, ServiceLocator => ServiceLocatorService }

import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters._
import scala.concurrent.{ ExecutionContext, Future }


class DnsServiceLocator @Inject() (
    @Named("ServiceLocatorService") serviceLocatorService: ActorRef,
    system: ActorSystem,
    implicit val ec: ExecutionContext) extends ServiceLocator {

  val settings = Settings(system)

  private def locateAsScala(name: String): Future[Option[URI]] =
    serviceLocatorService
      .ask(ServiceLocatorService.GetAddress(name))(settings.resolveTimeout1 + settings.resolveTimeout1 + settings.resolveTimeout2)
      .mapTo[ServiceLocatorService.Addresses]
      .map {
        case ServiceLocatorService.Addresses(addresses) =>
          addresses
            .headOption
            .map(sa => new URI(sa.protocol, null, sa.host, sa.port, null, null, null))
      }

  override def locate(name: String, serviceCall: Descriptor.Call[_, _]): CompletionStage[Optional[URI]] =
    locateAsScala(name).map(_.asJava).toJava

  override def doWithService[T](name: String, serviceCall: Descriptor.Call[_, _], block: JFunction[URI, CompletionStage[T]]): CompletionStage[Optional[T]] =
    locateAsScala(name).flatMap(uriOpt => {
      uriOpt.fold(Future.successful(Optional.empty[T])) { uri =>
        block.apply(uri)
          .toScala
          .map(v => Optional.of(v))
      }
    }).toJava
} 
开发者ID:typesafehub,项目名称:service-locator-dns,代码行数:49,代码来源:DnsServiceLocator.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Publisher类代码示例发布时间:2022-05-23
下一篇:
Scala FunSpecLike类代码示例发布时间: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