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

Scala Component类代码示例

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

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



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

示例1: ScalajHttpAdapter

//设置package包名称以及导入依赖的类
package com.piotrglazar.receiptlottery.utils

import org.springframework.beans.factory.annotation.{Autowired, Value}
import org.springframework.stereotype.Component

import scala.concurrent.{ExecutionContext, Future}
import scalaj.http.Http

@Component
class ScalajHttpAdapter @Autowired()(@Value("${http.timeouts:2000}") private val timeouts: Int) extends HttpAdapter {

  override def request(url: String, params: Map[String, String]): String =
    Http(url)
      .params(params)
      .timeout(timeouts, timeouts)
      .asString
      .body

  override def asyncRequest(url: String, params: Map[String, String])
                           (implicit executionContext: ExecutionContext): Future[String] =
    Future(request(url, params))
} 
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:23,代码来源:ScalajHttpAdapter.scala


示例2: ResultFetcher

//设置package包名称以及导入依赖的类
package com.piotrglazar.receiptlottery.core

import com.piotrglazar.receiptlottery.Token
import com.piotrglazar.receiptlottery.utils.HttpAdapter
import org.htmlcleaner.{HtmlCleaner, TagNode}
import org.springframework.beans.factory.annotation.{Autowired, Value}
import org.springframework.stereotype.Component

import scala.concurrent.{ExecutionContext, Future}

@Component
class ResultFetcher @Autowired()(@Value("${results.page}") private val pageAddress: String, private val httpAdapter: HttpAdapter,
                                 implicit private val executionContext: ExecutionContext) {

  def hasResult(token: Token): Future[Boolean] = {
    val rawContentFuture = httpAdapter.asyncRequest(pageAddress, Map("code" -> token.value))
    rawContentFuture.map { rawContent =>
      val cleanContent: TagNode = new HtmlCleaner().clean(rawContent)

      !getResultTables(cleanContent)
        .flatMap(getResultTableBody)
        .flatMap(getResultTableRows)
        .isEmpty
    }
  }

  private def getResultTables(page: TagNode): Array[TagNode] =
    page.getElementsByAttValue("class", "results-table", true, true)

  private def getResultTableBody(table: TagNode): Array[TagNode] =
    table.getElementsByName("tbody", true)

  private def getResultTableRows(tableBody: TagNode): Array[TagNode] =
    tableBody.getElementsByName("tr", true)
} 
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:36,代码来源:ResultFetcher.scala


示例3: WorkingActor

//设置package包名称以及导入依赖的类
package com.piotrglazar.receiptlottery.core

import akka.actor.Actor
import com.piotrglazar.receiptlottery.{Token, VerifiedToken}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component

@Component("workingActor")
@Scope("prototype")
class WorkingActor @Autowired()(private val resultFetcher: ResultFetcher) extends Actor {

  implicit private val executionContext = context.system.dispatcher

  override def receive: Receive = {
    case token: Token =>
      val requester = sender()
      val resultFuture = resultFetcher.hasResult(token)
      resultFuture.onSuccess { case result => requester ! VerifiedToken(token, result) }
  }
} 
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:22,代码来源:WorkingActor.scala


示例4: TokenReader

//设置package包名称以及导入依赖的类
package com.piotrglazar.receiptlottery.core

import com.piotrglazar.receiptlottery.Token
import org.springframework.beans.factory.annotation.{Value, Autowired}
import org.springframework.stereotype.Component
import rx.lang.scala.Observable

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

@Component
class TokenReader @Autowired()(@Value("${token.file}") private val path: String) {

  def readTokens(): Observable[Token] = {
    readContent() match {
      case Success(items) => Observable.from(items)
      case Failure(e) => Observable.error(e)
    }
  }

  private def readContent(): Try[List[Token]] =
    Try {
      Source.fromInputStream(getClass.getResourceAsStream(path))
        .getLines()
        .filter(!_.isEmpty)
        .map(Token)
        .toList
    }
} 
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:30,代码来源:TokenReader.scala


示例5: AdminSettingsDao

//设置package包名称以及导入依赖的类
package ch.mibex.bamboo.shipit.settings

import ch.mibex.bamboo.shipit.Logging
import com.atlassian.activeobjects.external.ActiveObjects
import com.atlassian.bamboo.security.EncryptionService
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport
import com.atlassian.sal.api.transaction.TransactionCallback
import net.java.ao.DBParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class AdminSettingsDao @Autowired()(@ComponentImport ao: ActiveObjects,
                                    @ComponentImport encryptionService: EncryptionService) extends Logging {

  import AoAdminSettings._

  // we cannot use @Transactional annotations but instead have to wrap our DB code into executeInTransaction
  // because this annotation cannot be used on Bamboo remote agents
  def createOrUpdate(vendorName: String, vendorPassword: String): AoAdminSettings =
    executeInTransaction(() => {
      ao.find[AoAdminSettings, Integer](classOf[AoAdminSettings]).headOption match {
        case Some(credentials) =>
          credentials.setVendorUserName(vendorName)
          credentials.setVendorPassword(encryptionService.encrypt(vendorPassword))
          credentials.save()
          credentials
        case None =>
          ao.create[AoAdminSettings, Integer](
            classOf[AoAdminSettings],
            new DBParam(VENDOR_USERNAME_COLUMN, vendorName),
            new DBParam(VENDOR_PASSWORD_COLUMN, encryptionService.encrypt(vendorPassword))
          )
      }
    })

  def find(): Option[AoAdminSettings] =
    executeInTransaction(() => ao.find[AoAdminSettings, Integer](classOf[AoAdminSettings]).headOption)

  private def executeInTransaction[T](fun: () => T) =
    ao.executeInTransaction(new TransactionCallback[T]() {
      override def doInTransaction(): T = fun()
    })

} 
开发者ID:mibexsoftware,项目名称:shipit2marketplace,代码行数:46,代码来源:AdminSettingsDao.scala


示例6: ShipItResultsLinkPanel

//设置package包名称以及导入依赖的类
package ch.mibex.bamboo.shipit.task

import java.util
import java.util.{Map => JMap}

import ch.mibex.bamboo.shipit.{Constants, Logging}
import com.atlassian.bamboo.chains.ChainResultsSummary
import com.atlassian.plugin.PluginAccessor
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport
import com.atlassian.plugin.web.model.AbstractWebPanel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import scala.collection.JavaConverters._


@Component
class ShipItResultsLinkPanel @Autowired()(@ComponentImport pluginAccessor: PluginAccessor)
  extends AbstractWebPanel(pluginAccessor) with Logging {

  private val MpacLogoBase64Encoded =
    """<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAQECAQEBAgICAgICAgICAQICAgICAgICAgL/2wBDAQEBAQEBAQEBAQECAQEBAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgL/wAARCABGACUDAREAAhEBAxEB/8QAHAAAAgICAwAAAAAAAAAAAAAAAAoICQYHAwUL/8QANRAAAAYCAQMCBAMGBwAAAAAAAQIDBAUGBwgJABESChMUFSFBFiJhFxgjJVFxMTI0YoGx8P/EABwBAAIDAQEBAQAAAAAAAAAAAAAHBQYIBAEDAv/EADsRAAIBAwMDAgEHCQkAAAAAAAECAwQFEQAGEgcTISIxQRQVMkJxkZIWI1FhcoKywcIzNUNEUoGhs8P/2gAMAwEAAhEDEQA/AH+OjRo6NGjo0aOjRo6NGuB06bMmzh48cItWjVFVy5cuVU0G7dugQyq666ypgKiiRMpjHMYQKUpRERAA69ALEKoLMxwAPJJPsAP068JCgsxwo8knwAB8TpQHZPnS2+3D2oPpbw10WFnnKD6RjH2wM/BR8+eURiFyNp27wLW0pnhKTi9koYQCXmmr9aSBZuLRs2WXat3T5s/TWw2Cy/lD1BqWiBAIpVYpxLDKxsU/OSTMP8OMqEweRYAkJW69QL3e7ubFsanWQgkGpZQ2Qpw0ih/RHEv+uQMW8cQCVBsMoukPNvWcfSV1n+WqAsmeCRfzKJxbIa4Y2lcFO5pECrGq87cFYJpLhEuex0Bko+GYLtPd94jZfw8TVWq3H06m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C1MgVu6c0amQkLMyaRQKH86sLdp8fOKD4F7qPHK6hhKAiYRDpaXO+Xm8v3LrdJ69s5AlkZlX9lCeC/YqjTBt1mtNpThbbdDRL7HtxqrH9pgOTfvE6kN1Fak9HRo0dGjR0aNHRo0dGjX//2Q=="/>"""

  // currently, there is no way to show a web panel on the environment of the deployment project,
  // see https://jira.atlassian.com/browse/BAM-13280
  override def getHtml(context: util.Map[String, AnyRef]): String = createMpacSubmissionLink(context)

  private def createMpacSubmissionLink(context: JMap[String, AnyRef]): String =
    context.get("resultSummary") match {
      case crs: ChainResultsSummary =>
        val pluginInfos = for {
          jobSummaries <- crs.getOrderedJobResultSummaries.asScala
          (key, pluginBinaryUrl) <- jobSummaries.getCustomBuildData.asScala if key == Constants.ResultLinkPluginBinaryUrl
          (key, pluginVersion) <- jobSummaries.getCustomBuildData.asScala if key == Constants.ResultLinkPluginVersion
        } yield (pluginBinaryUrl, pluginVersion)
        pluginInfos.toList match {
          case Nil => ""
          case (binaryUrl, version) :: _ =>
            s"""<p>$MpacLogoBase64Encoded <a href="$binaryUrl">Atlassian Marketplace version $version</a></p>"""
        }
      case _ => ""
    }

} 
开发者ID:mibexsoftware,项目名称:shipit2marketplace,代码行数:45,代码来源:ShipItResultsLinkPanel.scala


示例7: SubscribedArtifactCollector

//设置package包名称以及导入依赖的类
package ch.mibex.bamboo.shipit.task.artifacts

import java.io.File

import ch.mibex.bamboo.shipit.Utils
import com.atlassian.bamboo.plan.cache.ImmutableJob
import com.atlassian.bamboo.task.{CommonTaskContext, TaskContext}
import com.atlassian.bamboo.util.Narrow
import com.atlassian.bamboo.webwork.util.WwSelectOption
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport
import com.atlassian.sal.api.message.I18nResolver
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import scala.collection.JavaConverters._


@Component
class SubscribedArtifactCollector @Autowired() (@ComponentImport i18nResolver: I18nResolver) {

  def buildArtifactUiList(job: ImmutableJob): Seq[WwSelectOption] =
    job.getArtifactSubscriptions.asScala map { as =>
      val selectedValue = ArtifactSubscriptionId(as.getArtifactDefinition)
      val groupName = i18nResolver.getText("shipit.task.config.subscribed.artifacts")
      new WwSelectOption(as.getName, groupName, selectedValue.toString)
    }

  def findArtifactInSubscriptions(taskContext: CommonTaskContext, artifactId: Long): Option[File] = {
    val rootDir = taskContext.getWorkingDirectory
    val buildTaskContext = Narrow.downTo(taskContext, classOf[TaskContext])
    Option(buildTaskContext) flatMap { btc =>
      (btc.getBuildContext.getArtifactContext.getSubscriptionContexts.asScala collectFirst {
        case asc if asc.getArtifactDefinitionContext.getId == artifactId =>
          Utils.findMostRecentMatchingFile(asc.getArtifactDefinitionContext.getCopyPattern, rootDir)
      }).flatten
    }
  }

} 
开发者ID:mibexsoftware,项目名称:shipit2marketplace,代码行数:40,代码来源:SubscribedArtifactCollector.scala


示例8: TodoRepositoryOnDb

//设置package包名称以及导入依赖的类
package jp.ne.doilux.gohoubigazou.infrastructure

import jp.ne.doilux.gohoubigazou.domain.{Status, Todo, TodoRepository}
import org.springframework.stereotype.Component
import scalikejdbc._
import scalikejdbc.jsr310._


@Component
class TodoRepositoryOnDb extends TodoRepository {

  // initialize JDBC driver & connection pool
  Class.forName("org.h2.Driver")
  ConnectionPool.singleton("jdbc:h2:mem:todo", "sa", "")

  // ad-hoc session provider on the REPL
  implicit val session = AutoSession

  sql"""
create table todo (
  id int(10) NOT NULL AUTO_INCREMENT,
  title varchar(64),
  done int(1) default 0,
  created_at timestamp default current_timestamp
)
""".execute.apply()

  override def register(title: String): Unit = {
    sql"insert into todo(title) values (${title})".update.apply()
  }

  override def find: Seq[Todo] = {
    sql"select * from todo".map(
      rs => Todo(
        rs.int("id"),
        rs.string("title"),
        Status.createBy(rs.int("done")),
        rs.get("created_at")
      )
    ).list.apply()
  }

  override def save(obj: Todo): Unit = {
    val (status, id) = (obj.status.getIndex(), obj.id)
    sql"update todo set done = ${status} where id = ${id}"
      .update.apply()
  }

  override def find(id: Integer): Option[Todo] = {
    sql"SELECT * FROM todo where id = ${id}".map(
      rs => Todo(
        rs.int("id"),
        rs.string("title"),
        Status.createBy(rs.int("done")),
        rs.get("created_at")
      )
    ).single.apply()
  }
} 
开发者ID:m-doi,项目名称:gohoubigazou,代码行数:60,代码来源:TodoRepositoryOnDb.scala


示例9: SympathyDao

//设置package包名称以及导入依赖的类
package ru.izebit.dao

import org.bson.Document
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.{Criteria, Query}
import org.springframework.stereotype.Component
import ru.izebit.model.Sympathy

import scala.collection.JavaConversions._

@Component
class SympathyDao {

  private val sympathyTableName = "sympathies"

  @Autowired
  private var mongoTemplate: MongoTemplate = _

  def dropAll(): Unit = {
    mongoTemplate.getCollectionNames.foreach(name => mongoTemplate.dropCollection(name))
  }

  def insert(sympathy: Sympathy): Unit =
    mongoTemplate.save(
      new Document()
        .append("_id", sympathy.id)
        .append("sympathy", sympathy),
      sympathyTableName)

  def get(id: String): Sympathy = {
    val document = mongoTemplate.findById(id, classOf[Document], sympathyTableName)

    if (document == null)
      Sympathy(id, Set.empty)
    else
      document.get("sympathy", classOf[Sympathy])
  }

  def removeFor(id: String): Unit =
    mongoTemplate.remove(new Query().addCriteria(Criteria.where("_id").is(id)), sympathyTableName)
} 
开发者ID:android-group,项目名称:night-meet,代码行数:43,代码来源:SympathyDao.scala


示例10: SocialNetworkProvider

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

import java.util.concurrent.TimeUnit

import org.apache.http.client.fluent.Request
import org.json.JSONObject
import org.springframework.stereotype.Component
import ru.izebit.model.Sex

import scala.collection.JavaConversions.asScalaIterator


@Component
class SocialNetworkProvider {
  private val API_VERSION = "5.62"

  private val TIMEOUT = TimeUnit.SECONDS.toMillis(5).asInstanceOf[Int]
  private val HOST = "https://api.vk.com/method/"


  
  def search(city: Int, sex: Sex, count: Int, offset: Int, token: String): List[String] = {

    val isEnableExternalSearch = java.lang.Boolean.getBoolean("external-search-enable")
    if (!isEnableExternalSearch)
      return List.empty

    val sortType = 1
    val isHasPhoto = 1
    val online = 1
    val status = 6

    val param = s"users.search?" +
      s"city=$city&sex=$sex&count=$count&offset=$offset" +
      s"&sort=$sortType&status=$status&online=$online&has_photo=$isHasPhoto" +
      s"&access_token=$token&v=$API_VERSION"

    //todo ??????? ????????? ???????? ??????? ? ?????? ?????
    val content =
      Request
        .Get(HOST + param)
        .connectTimeout(TIMEOUT)
        .execute().returnContent().asString()

    val jsonResponse = new JSONObject(content)

    jsonResponse
      .getJSONArray("items")
      .iterator()
      .map(e => e.asInstanceOf[JSONObject])
      .map(e => e.getString("id"))
      .toList
  }
} 
开发者ID:android-group,项目名称:night-meet,代码行数:55,代码来源:SocialNetworkProvider.scala


示例11: DocumentsLoader

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

import java.io.File

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import scala.io.Source

@Component
class DocumentsLoader {

  @Autowired
  var client : DocumentsClient = _

  def loadDocument(folder: String, baseName: String, documentType: String): Unit = {
    val json = Source.fromFile(new File(folder + "/" + baseName + ".json")).mkString
    val content = Source.fromFile(new File(folder + "/" + baseName + "." + documentType)).mkString
    val jsonMapper = new ObjectMapper()
    val header = jsonMapper.readValue(json, classOf[Document])
    header.content = content

//    val res : String = client.post(header)

    System.out.println("POSTED " + baseName + ", response= " + 2)
  }

  def loadDocuments(folder: String, documentType: String): Unit = {
    val file = new File(folder)
    if (!file.isDirectory || !file.exists()) {
      throw new IllegalArgumentException("No such filder " + folder)
    }
    file.listFiles
      .filter(f => f.isFile & f.getName.endsWith(".json"))
      .map(_.getName)
      .map(n => n.substring(0, n.length - ".json".length))
      .foreach(loadDocument(folder, _, documentType))
  }

} 
开发者ID:kolov,项目名称:curri-docs-service,代码行数:42,代码来源:DocumentsLoader.scala


示例12: StatisticsAdvice

//设置package包名称以及导入依赖的类
package com.github.yingzhuo.springboot.scala.demo.aop

import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.{Around, Aspect}
import org.aspectj.lang.reflect.MethodSignature
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component

@Aspect
@Component
@Profile(Array("!release"))
class StatisticsAdvice {

    private[this] val logger = LoggerFactory.getLogger(classOf[StatisticsAdvice])

    @Around("execution(public * com.github.yingzhuo..service.*.*(..))")
    def around(joinPoint: ProceedingJoinPoint): Any = {
        var ex: Throwable = null

        val t1 = System.currentTimeMillis()

        val result = try {
            joinPoint.proceed()
        } catch {
            case e: Throwable => ex = e
        }

        val t2 = System.currentTimeMillis()

        joinPoint.getSignature match {
            case ms: MethodSignature =>
                val method = ms.getMethod
                logger.debug("method: {} => {} millis", method.getName, t2 - t1)
            case _ =>
        }

        ex match {
            case null => result
            case _ => throw ex
        }
    }
} 
开发者ID:yingzhuo,项目名称:springboot-scala-demo,代码行数:44,代码来源:StatisticsAdvice.scala


示例13: StandardOutMessageRenderer

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

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component("renderer") class StandardOutMessageRenderer extends MessageRenderer {
  @Autowired private val messageProvider: MessageProvider = null

  override def render {
    if (messageProvider == null) {
      throw new RuntimeException("You must set the property messageProvider of class:"
        + classOf[StandardOutMessageRenderer].getName)
    }
    println(messageProvider.getMessage)
  }
} 
开发者ID:BBK-PiJ-2015-67,项目名称:sdp-portfolio,代码行数:17,代码来源:StandardOutMessageRenderer.scala


示例14: OrdersDynamoSchema

//设置package包名称以及导入依赖的类
package works.weave.socks.aws.orders.dataaccess.dynamo

import com.amazonaws.services.dynamodbv2.model._
import org.springframework.stereotype.Component
import works.weave.socks.spring.aws.DynamoConfiguration
import works.weave.socks.spring.aws.DynamoSchema


@Component
class OrdersDynamoSchema(dynamoConnection : DynamoConfiguration) extends DynamoSchema(dynamoConnection) {

  override protected def schema(declare : (CreateTableRequest) => Any) : Unit = {

    declare(
      table(name = "orders",
        attributeDefinitions = Seq(
          attributeDefinition("id", ScalarAttributeType.S),
          attributeDefinition("customerId", ScalarAttributeType.S)),
        keySchema = Seq(
          keySchemaElement("id", KeyType.HASH),
          keySchemaElement("customerId", KeyType.RANGE)),
        provisionedThrougput = new ProvisionedThroughput(1L, 1L)))

  }
} 
开发者ID:Compositional,项目名称:orders-aws,代码行数:26,代码来源:OrdersDynamoSchema.scala


示例15: Server

//设置package包名称以及导入依赖的类
package works.weave.socks.aws.orders.main

import org.eclipse.jetty
import org.eclipse.jetty.servlet.ServletContextHandler
import org.eclipse.jetty.servlet.ServletHolder
import org.glassfish.jersey.servlet.ServletContainer
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import scala.collection.JavaConverters._
import scala.util.control.NonFatal
import Server._
import org.eclipse.jetty.util.log.Slf4jLog

@Component
class Server(val jerseyApp : JerseyApp) {

  def run() : Unit = {

    jetty.util.log.Log.setLog(new Slf4jLog())

    val port = System.getenv().asScala.getOrElse("PORT", "80").toInt

    val context = new ServletContextHandler(ServletContextHandler.SESSIONS)
    context.setContextPath("/")

    val jettyServer = new jetty.server.Server(port)
    jettyServer.setHandler(context)

    val servletContainer = new ServletContainer(jerseyApp)
    val servletHolder = new ServletHolder(servletContainer)
    context.addServlet(servletHolder, "/*")
    val jerseyServlet = servletHolder
    jerseyServlet.setInitOrder(0)

    try {
      Log.info("Starting jetty")
      jettyServer.start()
      Log.info("Jetty started")
      jettyServer.join()
      Log.info("Jetty exited")
    } finally {
      Log.info("Destroying jetty")
      try {
        jettyServer.destroy()
      } catch {
        case NonFatal(e) => Log.error("Error during Jetty shutdown", e)
      }
    }
  }
}

object Server {
  val Log = LoggerFactory.getLogger(classOf[Server])
} 
开发者ID:Compositional,项目名称:orders-aws,代码行数:55,代码来源:Server.scala


示例16: ProjectDataGathererImpl

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

import com.github.tweets.common.ProjectData
import com.github.tweets.gateway.{TwitterAPIGateway, GitHubAPIGateway}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
private[tweets] class ProjectDataGathererImpl @Autowired()(gitHubAPIGateway: GitHubAPIGateway,
                                                           twitterAPIGateway: TwitterAPIGateway) extends ProjectDataGatherer {
  override def gatherProjectData(keyword: String): Seq[ProjectData] = {
    val topProjects = gitHubAPIGateway.fetchTopProjects(keyword)

    topProjects.map(githubProject => ProjectData(githubProject, twitterAPIGateway.fetchTweets(githubProject)))
  }
}

private[tweets] trait ProjectDataGatherer {
  def gatherProjectData(keyword: String): Seq[ProjectData]
} 
开发者ID:andrei-l,项目名称:tweets-for-github-projects-gatherer,代码行数:21,代码来源:ProjectDataGatherer.scala


示例17: TwitterAuthorizationRequest

//设置package包名称以及导入依赖的类
package com.github.tweets.gateway.twitter

import java.nio.charset.Charset
import java.util.Base64

import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component

private[twitter] object TwitterAuthorizationRequest {
  def apply(): String = "grant_type=client_credentials"
}

private[twitter] case class TwitterAuthorizationResponse(@JsonProperty("token_type") tokenType: String,
                                                         @JsonProperty("access_token") accessToken: String)

@Component
private[twitter] class TwitterAuthorizationData {

  @Value("${twitter.consumer.key}")
  private val twitterConsumerKey = ""

  @Value("${twitter.consumer.secret}")
  private val twitterConsumerSecret = ""

  lazy val bearerTokenCredentials =
    encodeBase64(s"$twitterConsumerKey:$twitterConsumerSecret")

  private def encodeBase64(s: String): String =
    Base64.getEncoder.encodeToString(s.getBytes(Charset.defaultCharset()))
} 
开发者ID:andrei-l,项目名称:tweets-for-github-projects-gatherer,代码行数:32,代码来源:TwitterAuthorizationExchange.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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