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

Scala Service类代码示例

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

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



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

示例1: ItalianVATIdNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.pdfextractor.algorithm.candidate.Candidate
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.VATIN
import org.pdfextractor.db.domain.dictionary.{PaymentFieldType, SupportedLocales}
import org.springframework.stereotype.Service

import scala.collection.mutable
import scala.util.matching.Regex

@Service
class ItalianVATIdNumberFinder
  extends AbstractFinder(SupportedLocales.ITALY, VATIN, ItVatinR, ItVatinValueR, true, true) {

 override def searchValuesFromPhrase(
                                       phrase: Phrase,
                                       parseResult: ParseResult,
                                       valuePattern2: Regex): mutable.Buffer[Candidate] = {
    searchPattern.get
      .findAllIn(parseResult.text)
      .map(getValuePattern.findAllIn(_))
      .filter(isValueAllowed(_))
      .map(buildCandidate1(_))
      .toBuffer
  }

  override def isValueAllowed(value: Any): Boolean = {
    Option(value).isDefined &&
      value.isInstanceOf[String] &&
      value.asInstanceOf[String].length == 11 &&
      value.asInstanceOf[String].matches("""\d*""")
  }

  override def parseValue(raw: String): Any = raw

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:42,代码来源:ItalianVATIdNumberFinder.scala


示例2: ItalianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{CandidateMetadata, MetaPhraseType}
import org.pdfextractor.algorithm.finder._
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class ItalianNameFinder extends AbstractFinder(SupportedLocales.ITALY, NAME, None, None, false) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?ims)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ITALY,
        NAME) + "$").r)
    valuePattern = Some(("^(?ims)(.*)$").r)
  }

  def isValueAllowed(value: Any): Boolean = {
    !isVoidText(value.asInstanceOf[String]) &&
      ItNameForbiddenWordsR.findFirstIn(value.asInstanceOf[String]).isEmpty &&
      ItNameMinR.findFirstIn(value.asInstanceOf[String]).nonEmpty
  }

  def parseValue(raw: String): Any = {
    if (Option(raw).isEmpty) None
    else StringUtils.normalizeSpace(raw).split(",")(0)
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ITALY, NAME, phrase.text)
    Map(MetaPhraseType -> phraseType)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:45,代码来源:ItalianNameFinder.scala


示例3: EstonianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{Candidate, CandidateMetadata, HasPank, MetaPhraseType}
import org.pdfextractor.algorithm.finder.{AbstractFinder, isPankPresent}
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianNameFinder extends AbstractFinder(SupportedLocales.ESTONIA, NAME) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?m)" + phraseTypesStore
        .buildAllStarts(SupportedLocales.ESTONIA, NAME) + "$").r)
    valuePattern = Some(
      ("(?m)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        NAME)).r)
  }

  override def isValueAllowed(value: Any) = true

  override def parseValue(raw: String): Any = {
    StringUtils normalizeSpace (raw
      .replaceAll("(Registrikood)(.{0,})", "")
      .split("""[\s]{3,}""")(0))
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ESTONIA, NAME, phrase.text)
    val pankPresent = isPankPresent(phrase.text)
    Map(MetaPhraseType -> phraseType, HasPank -> pankPresent)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:43,代码来源:EstonianNameFinder.scala


示例4: EstonianReferenceNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.math.BigInteger
import java.util.Locale

import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.finder.{AbstractFinder, _}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.REFERENCE_NUMBER
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianReferenceNumberFinder extends AbstractFinder(SupportedLocales.ESTONIA, REFERENCE_NUMBER, EstRefNoLineR, EstRefNoR) {

  override def parseValue(raw: String): Any = raw

  override def isValueAllowed(raw: Any): Boolean = {
    try {
      val value = new BigInteger(raw.asInstanceOf[String])
      isCorrectFormat(value) && checkDigitMatches(value,
        calculateCheckDigit(value))
    } catch {
      case _: Throwable => false
    }
  }

  private def calculateCheckDigit(value: BigInteger) = {
    val productsSum = calculate731Sum(digitsToPenultimateInReverse(value))

    findTensMultiple(productsSum) - productsSum
  }

  private def checkDigitMatches(value: BigInteger, checkDigit: Int) = {
    val lastDigit =
      Integer.valueOf("" + value.toString.charAt(value.toString.length - 1))
    lastDigit == checkDigit
  }

  private def isCorrectFormat(value: BigInteger): Boolean = {
    Option(value).isDefined &&
      value.signum > 0 && // must be positive
      value.toString.length >= 2 && // must have 2 - 20 digits
      value.toString.length <= 20
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:47,代码来源:EstonianReferenceNumberFinder.scala


示例5: EstonianInvoiceIDFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.INVOICE_ID
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianInvoiceIDFinder extends AbstractFinder(SupportedLocales.ESTONIA, INVOICE_ID) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("(?ism)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        INVOICE_ID)).r)
    valuePattern = Some(("(?ism)" + phraseTypesStore.buildAllPhrases(
      SupportedLocales.ESTONIA,
      INVOICE_ID) +
      """([.]{0,1})([\s]{0,})([:]{0,1})([\s]{0,})([^\s]{1,})""").r)
  }

  override def isValueAllowed(value: Any): Boolean = {
    EstIBANCorrectR
      .findFirstIn(value.asInstanceOf[String])
      .isEmpty &&
      TwoOrMoreDigitsR
        .findFirstIn(value.asInstanceOf[String])
        .nonEmpty
  }

  override def parseValue(raw: String): Any = StringUtils.normalizeSpace(raw)

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:41,代码来源:EstonianInvoiceIDFinder.scala


示例6: RelationBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans
import javax.annotation.Resource
import org.springframework.stereotype.Service
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.Relation
import javax.annotation.Resource
@org.springframework.stereotype.Service
class RelationBean (@Resource(name = "daoImpl") val dao: DaoCrud){
  val clazz = classOf[Relation]
	def persist (relation:Relation) = dao.persist(relation)
	def persistAll(relations :List[Relation]) = dao.persistAll(relations)
	def find() = dao.find(clazz);
	def merge(relation:Relation) = dao.merge(relation);
	def delete(relation:Relation) = dao.delete(relation)
	//def readSort(comparator:Comparator[Relation])
	

} 
开发者ID:writeonly,项目名称:babel,代码行数:19,代码来源:RelationBean.scala


示例7: RecordBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans
import javax.annotation.Resource
import java.io.BufferedReader
import org.springframework.stereotype.Service
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.Record
import pl.writeonly.babel.entities.User
import pl.writeonly.scala.util.ToBoolean
import scala.collection.mutable.MutableList
import pl.writeonly.babel.entities.Relation

@org.springframework.stereotype.Service
class RecordBean(@Resource(name = "daoImpl") val dao: DaoCrud) extends ToBoolean {
  val clazz = classOf[Record]
  def persist(record: Record) = dao.persist(record)
  def persistAll(records: List[Record]) = dao.persistAll(records)
  def find(user: User) = dao.find(clazz);
  def find() = dao.find(clazz)
  def merge(record: Record) = dao.merge(record);

  def parse(reader: BufferedReader): MutableList[Record] = {
    val list = new MutableList[Record]
    do {
      val line: String = reader.readLine
      if (!line) return list
      list += new Record(line)
      var i: Int = new Integer(line).toInt
    } while (true)
    return null
  }
  
  def toRecordAll(relations : List[Relation]) = {
    
  }
} 
开发者ID:writeonly,项目名称:babel,代码行数:36,代码来源:RecordBean.scala


示例8: InfoService

//设置package包名称以及导入依赖的类
package com.github.swwjf.ws

import com.github.swwjf.errorhandling.WSException
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

import scala.collection.JavaConversions._
import scala.compat.java8.OptionConverters.RichOptionalGeneric

@Service
class InfoService @Autowired()(infoRepository: InfoRepository) {

  def fetchAllInformation(): List[InfoResponseDTO] = {
    def jpaToResponse(jpa: InfoJPA): InfoResponseDTO = {
      val response = InfoResponseDTO(
        createdDate = jpa.createdData.toString,
        updatedDate = Option(jpa.updatedDate).map(_.toString).orNull
      )
      BeanUtils.copyProperties(jpa, response)
      response
    }

    infoRepository
      .findAll()
      .map(jpaToResponse)
      .toList
  }

  def saveInfo(infoRequestDTO: InfoRequestDTO): Unit = {
    def requestToJPA(request: InfoRequestDTO): InfoJPA = {
      val jpa = new InfoJPA
      BeanUtils.copyProperties(request, jpa)
      jpa
    }

    try {
      infoRepository.save(requestToJPA(infoRequestDTO))
    } catch {
      case e: DataIntegrityViolationException => throw new WSException("Invalid/duplicate label")
    }
  }

  @Transactional
  def updateInfo(info: InfoRequestDTO): Unit = {
    val infoJPA = infoRepository
      .findOneByLabel(info.label)
      .asScala
      .getOrElse(throw new WSException(s"Failed to find info by label ${info.label}"))
    infoJPA.setMainDetails(info.mainDetails)
    infoJPA.setComments(info.comments)
  }

} 
开发者ID:andrei-l,项目名称:scala-webapp-with-java-frameworks,代码行数:57,代码来源:InfoService.scala


示例9: VoteService

//设置package包名称以及导入依赖的类
package org.helianto.politikei.service

import org.helianto.politikei.{Proposition, Vote}
import org.helianto.politikei.repository.{PropositionRepository, VoteRepository}
import org.springframework.data.domain.{PageRequest, Sort}
import org.springframework.stereotype.Service

@Service
class VoteService(val repository: VoteRepository, val propositionRepository: PropositionRepository) {

  private[service] def page(page: Int) = new PageRequest(page, 10, Sort.Direction.ASC, "voteDate")

  def all(propositionId: String, p: Int = 0) = repository.findByPropositionId(Option(propositionId).getOrElse(""), page(0))

  def one(voteId: String) = repository.findOne(Option(voteId).getOrElse(""))

  def me(propositionId: String, identityId: String) =
    repository.findByPropositionIdAndIdentityId(Option(propositionId).getOrElse(""), identityId)

  def saveOrUpdate(propositionId: String, identityId: String, value: Int) = {
    require(Option(propositionId).nonEmpty)
    require(Option(identityId).nonEmpty)
    Option(propositionRepository.findOne(propositionId)) match {
      case Some(proposition) =>
        val vote = repository.save {
          Option(repository.findByPropositionIdAndIdentityId(propositionId, identityId))
            .getOrElse(new Vote(propositionId, identityId))
            .merge(value)
        }
        applyTo(proposition)
        vote
      case None => throw new IllegalArgumentException("Proposition must not be null")
    }
  }

  private[service] def applyTo(proposition: Proposition) = {
    import collection.JavaConversions._
    repository.countVote(proposition.id).toList.foreach{i =>
      println(s"VOTE: $i")
      proposition.merge(i)}
    propositionRepository.save(proposition)
  }

} 
开发者ID:iservport,项目名称:iservport-politikei,代码行数:45,代码来源:VoteService.scala


示例10: TasksRepository

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import com.github.mkorman9.districron.{ExecutionStatus, Success}
import com.github.mkorman9.districron.common.ExecutionLock
import com.github.mkorman9.districron.dao.TasksDAO
import com.github.mkorman9.districron.model.Task
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TasksRepository @Autowired() (tasksDAO: TasksDAO) {
  def readAll: Seq[Task] = {
    tasksDAO.readAll map (new Task(_))
  }

  // locks execution of given task definition to current node
  // returns if lock was created successfully
  def tryToEstablishExecutionLock(task: Task): ExecutionLock = {
    tasksDAO.createTaskExecutionIfThereIsNoOngoingOneInGivenPeriod(
      task.name,
      task.executionInterval
    )
  }

  def markTaskExecutionCompleted(executionId: Long, status: ExecutionStatus): Unit = {
    tasksDAO.updateTaskExecutionStatus(
      executionId,
      status == Success
    )
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:32,代码来源:TasksRepository.scala


示例11: MessageSender

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import akka.actor.{ActorRef, ActorSystem}
import akka.cluster.pubsub.DistributedPubSubMediator.{Publish, Send}
import com.github.mkorman9.districron.Messages.ExecuteTask
import com.github.mkorman9.districron.model.Task
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class MessageSender @Autowired() (actorSystem: ActorSystem) {
  def sendMessageToTasksHandlingActor(message: Any): Unit = {
    val tasksHandlingActor = actorSystem.actorSelection(com.github.mkorman9.districron.Actor.Path)
    tasksHandlingActor ! message
  }

  def broadcastExecutionMessage(clusterMediator: ActorRef, sender: ActorRef, executionId: Long, task: Task): Unit = {
    val executeTaskMessage = ExecuteTask(executionId, task.name)

    if (task.globalDistribution)
      clusterMediator.tell(
        Publish(task.recipient, executeTaskMessage),
        sender
      )
    else
      clusterMediator.tell(
        Send(task.recipient, executeTaskMessage, localAffinity = false),
        sender
      )
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:32,代码来源:MessageSender.scala


示例12: TasksManager

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import com.github.mkorman9.districron.ExecutionStatus
import com.github.mkorman9.districron.actor.Messages.BroadcastTaskExecutionToRecipients
import com.github.mkorman9.districron.model.Task
import org.slf4j.{Logger, LoggerFactory}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TasksManager @Autowired() (tasksRepository: TasksRepository, tasksScheduler: TasksScheduler, messageSender: MessageSender) {
  final val logger: Logger = LoggerFactory.getLogger(classOf[TasksManager])

  def scheduleAllExistingTasks: Unit = {
    tasksScheduler.schedule(tasksRepository.readAll)
  }

  def executeTask(task: Task): Unit = {
    logger.info(s"Trying to get lock for ${task.name}")
    val executionLock = tasksRepository.tryToEstablishExecutionLock(task)

    executionLock match {
      case Some(executionId) => performTaskExecution(executionId, task)
      case None => logger.info(s"Lock for ${task.name} already established by someone else. Skipping execution")
    }
  }

  def completeTaskExecution(executionId: Long, status: ExecutionStatus): Unit = {
    logger.info(s"Task execution $executionId completed with status $status")
    tasksRepository.markTaskExecutionCompleted(executionId, status)
  }

  private def performTaskExecution(executionId: Long, task: Task): Unit = {
    logger.info(s"Lock for ${task.name} established. Proceeding with execution")

    messageSender sendMessageToTasksHandlingActor BroadcastTaskExecutionToRecipients(executionId, task)
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:39,代码来源:TasksManager.scala


示例13: TasksScheduler

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import java.util.Date

import com.github.mkorman9.districron.actor.Messages.TaskExecutionTick
import com.github.mkorman9.districron.model.Task
import org.slf4j.{Logger, LoggerFactory}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.support.CronTrigger
import org.springframework.scheduling.{TaskScheduler, Trigger, TriggerContext}
import org.springframework.stereotype.Service

@Service
class TasksScheduler @Autowired() (systemScheduler: TaskScheduler,
                                   messageSender: MessageSender) {
  final val logger: Logger = LoggerFactory.getLogger(classOf[TasksScheduler])

  def schedule(tasks: Seq[Task]): Unit = {
    tasks foreach schedule
  }

  def schedule(task: Task): Unit = {
    logger.info(s"Scheduling task '${task.name}'...")

    systemScheduler.schedule(
      TaskRunnable(task, messageSender),
      CronTriggerConfiguration(task.cronExpression)
    )
  }
}

case class CronTriggerConfiguration(cronExpression: String) extends Trigger {
  final val logger: Logger = LoggerFactory.getLogger(classOf[CronTriggerConfiguration])

  override def nextExecutionTime(triggerContext: TriggerContext): Date = {
    try {
      val trigger = new CronTrigger(cronExpression)
      trigger.nextExecutionTime(triggerContext)
    }
    catch {
      case e: IllegalArgumentException => {
        logger.error(s"Error while scheduling task! Invalid cron expression '$cronExpression'")
        null
      }
    }
  }
}

case class TaskRunnable(task: Task, messageSender: MessageSender) extends Runnable {
  override def run(): Unit = {
    messageSender sendMessageToTasksHandlingActor TaskExecutionTick(task)
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:54,代码来源:TasksScheduler.scala


示例14: EchoService

//设置package包名称以及导入依赖的类
package org.helianto.mailer.service

import com.iservport.message.domain.Message
import org.springframework.stereotype.Service

@Service
class EchoService {

  def handle(message: Message) = {
    val received =
      s"""
         |On-line:  [ link ${message.getDefaults.seeOnline} ${message.getDefaults.apiHome}/redirect/${message.getTemplate}/${message.getId} ]
         |
         |id:       ${message.getId}
         |
         |Sent by:  ${message.getSender.contactName} <${message.getSender.contactEmail}>
         |Entity:   ${message.getSender.entityName}
         |Address:  ${message.getSender.address}
         |
         |To:       ${message.getRecipient.contactName} <${message.getRecipient.contactEmail}>
         |Entity:   ${message.getRecipient.entityName}
         |Address:  ${message.getRecipient.address}
         |
         |Subject:  ${message.getMessageData.subject} <${message.getMessageData.title}>
         |
         |${message.getDefaults.greeting}, ${message.getRecipient.contactName}
         |
         |${message.getMessageData.procedure}
         |
         |[ button -> ${message.getMessageData.callToAction} ]
         |
         |${message.getMessageData.fallBack}
         |
         |[ link -> ${message.getDefaults.apiHome}${message.getServicePath}/${message.getId} ]
         |
         |----
         |
         |${message.getDefaults.sentByText} ${message.getSender.contactEmail}
         |${message.getDefaults.disclaimer}
         |${message.getDefaults.ensure}
         |${message.getDefaults.unsubscribeText}, [ link ${message.getDefaults.unsubscribeCaption} -> ${message.getDefaults.apiHome}/${message.getDefaults.unsubscribeService} ]
         |${message.getDefaults.copyright}
         |
       """.stripMargin
    println(received)
    received
  }

} 
开发者ID:iservport,项目名称:helianto-echo-mailer,代码行数:50,代码来源:EchoService.scala


示例15: AtlantaScalaMicroservice

//设置package包名称以及导入依赖的类
package com.ntsdev.http

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import com.ntsdev.config.EnvironmentConfig
import com.ntsdev.http.routes.{HtmlRoutes, JsonRoutes, TwitterRoutes}
import com.ntsdev.service.{PersonService, TwitterService}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import com.softwaremill.session.{SessionConfig, SessionManager, SessionUtil}
import org.springframework.context.annotation.Primary

import scala.concurrent.{ExecutionContext, Future}

@Service
@Primary
class AtlantaScalaMicroservice extends Directives with EnvironmentConfig {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val executor: ExecutionContext = system.dispatcher

  private val sessionConfig = SessionConfig.default(SessionUtil.randomServerSecret())
  implicit val sessionManager = new SessionManager[Map[String, String]](sessionConfig)

  var _personService: PersonService = _

  private val logger = Logging(system, getClass)
  private val htmlRoutes = new HtmlRoutes()
  private val jsonRoutes = new JsonRoutes(_personService)
  private val twitterRoutes = new TwitterRoutes(new TwitterService)

  @Autowired
  def personService_=(service: PersonService){ //TODO: fix spring lifecycle ordering
    _personService = service
    jsonRoutes.personService = service
  }

  def routes = {
    htmlRoutes.route ~ jsonRoutes.route ~ twitterRoutes.route
  }

  logger.info("Starting http server...")

  Http().bindAndHandle(routes, interface, port).flatMap(binding => {
    logger.info(s"Listening on port [$port] interface [$interface]")
    Future.successful(binding)
  })


} 
开发者ID:neilshannon,项目名称:atlanta-scala-microservice,代码行数:54,代码来源:AtlantaScalaMicroservice.scala


示例16: TestDataService

//设置package包名称以及导入依赖的类
package com.ntsdev.service

import java.util.Collections

import org.neo4j.ogm.session.Session
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.{Propagation, Transactional}

import scala.collection.JavaConversions._
import scala.io.{Codec, Source}

@Service
@Profile(Array("!cloud"))
@Transactional(propagation = Propagation.REQUIRED)
class TestDataService {
  private val log = LoggerFactory.getLogger(getClass)
  private var loaded = false

  @Autowired
  val session: Session = null

  def loadTestData() = {
    session.purgeDatabase()
    log.info ("Loading test data...")

    val emptyMap = mapAsJavaMap[String, AnyRef](Collections.emptyMap[String, AnyRef]())
    session.query(loadDataFromFile("testdata.cql"), emptyMap)

    log.info("Test data loaded.")
    loaded = true
  }

  private def loadDataFromFile(fileName: String): String = {
    Source.fromURL(getClass.getResource("/" + fileName))(Codec.UTF8).mkString
  }

} 
开发者ID:neilshannon,项目名称:atlanta-scala-microservice,代码行数:41,代码来源:TestDataService.scala


示例17: PersonService

//设置package包名称以及导入依赖的类
package com.ntsdev.service

import com.ntsdev.domain.Person
import com.ntsdev.repository.PersonRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

import scala.collection.Iterable
import scala.collection.JavaConversions._

@Service
class PersonService {

  @Autowired
  val personRepository: PersonRepository = null

  
  def peopleWithContactsDepthOne: Iterable[Person] = {
    val people: Iterable[Person] = personRepository.findConnections

    def clearConnections(contact: Person) = {
      contact.copy(contacts = Set.empty[Person])
    }

    people.map(rootPerson => {
      val personContacts: Set[Person] = rootPerson.contacts.toSet
      val subContacts: Set[Person] = personContacts.map(clearConnections)
      rootPerson.copy(contacts = subContacts)
    })
  }
} 
开发者ID:neilshannon,项目名称:atlanta-scala-microservice,代码行数:32,代码来源:PersonService.scala


示例18: ProjectService

//设置package包名称以及导入依赖的类
package org.helianto.hackabase.service

import org.helianto.hackabase.domain.Project
import org.helianto.hackabase.repository.ProjectRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ProjectService {

  @Autowired val projectRepository: ProjectRepository = null

  def list = projectRepository.findAll

  def get(id: String) = projectRepository.findOne(id)

  def create(entityId: String) = new Project(entityId)

  def saveOrUpdate(command: Project) = {
    val project = Option(projectRepository.findOne(command.id)) match {
      case Some(p) => p
      case None => new Project(command.entityId)
    }
    project.projectName = command.projectName
    project.projectDesc = command.projectDesc
    projectRepository.saveAndFlush(project)
  }

} 
开发者ID:iservport,项目名称:hackabase,代码行数:30,代码来源:ProjectService.scala


示例19: TeamService

//设置package包名称以及导入依赖的类
package org.helianto.hackabase.service

import org.helianto.hackabase.domain.Team
import org.helianto.hackabase.repository.TeamRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TeamService {

  @Autowired val teamRepository: TeamRepository = null

  def list(projectId: String) = teamRepository.findByProjectId(projectId)

  def get(id: String) = teamRepository.findOne(id)

  def create(projectId: String) = new Team(projectId)

  def saveOrUpdate(command: Team) = {
    val team = Option(teamRepository.findOne(command.id)) match {
      case Some(t) => t
      case None => new Team(command.projectId)
    }
    team.identityId = command.identityId
    team.identityName = command.identityName
    team.joined = command.joined
    team.imageUrl = command.imageUrl
    team.currentRole = command.currentRole
    teamRepository.saveAndFlush(team)
  }

} 
开发者ID:iservport,项目名称:hackabase,代码行数:33,代码来源:TeamService.scala


示例20: CarService

//设置package包名称以及导入依赖的类
package com.example.cloud.service

import com.example.cloud.logging.Logging
import com.example.cloud.model.BookedCar
import com.example.cloud.remote.{Car, RemoteCarService, RemoteUserService}
import com.example.cloud.repository.BookedCarRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

import scala.collection.JavaConversions._
import scala.util.Try

@Service
class CarService extends Logging {
  @Autowired
  var bookedCarRepository: BookedCarRepository = _
  @Autowired
  var remoteCarService: RemoteCarService = _
  @Autowired
  var remoteUserService: RemoteUserService = _

  def getAvailableCars(): Try[Seq[Car]] = Try {
      remoteCarService.getAllCars().filterNot(car => getBookedCarIds.contains(car.id))
    }

  def getBookedCarIds: Seq[String] = {
    bookedCarRepository.findAll().map(bc => bc.carId)
  }

  def bookCar(userId: String, carId: String): BookedCar = {
    val user = remoteUserService.getUserById(userId)
    val car = remoteCarService.getCarById(carId)
    log.info(s"User: ${user} booked car: ${car}")
    bookedCarRepository.save(BookedCar(user.id, car.id))
  }

  def returnCar(carId: String) = {
    bookedCarRepository.deleteByCarId(carId)
  }
} 
开发者ID:okharkovskyi,项目名称:scala-cloud-skeleton,代码行数:41,代码来源:CarService.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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