本文整理汇总了Scala中java.util.Optional类的典型用法代码示例。如果您正苦于以下问题:Scala Optional类的具体用法?Scala Optional怎么用?Scala Optional使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Optional类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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()
}
}
示例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()))
}
}
示例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)
}
)
}
}
示例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)
}
}
示例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])
示例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)
}
}
}
示例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)
}
}
}
示例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)
}
}
示例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
}
}
示例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]
}