本文整理汇总了Scala中com.google.api.client.googleapis.auth.oauth2.GoogleCredential类的典型用法代码示例。如果您正苦于以下问题:Scala GoogleCredential类的具体用法?Scala GoogleCredential怎么用?Scala GoogleCredential使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GoogleCredential类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: HttpInitializer
//设置package包名称以及导入依赖的类
package mn.clarkson.google.pubsub
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.http._
import java.io.IOException
import com.google.api.client.util.{ExponentialBackOff, Sleeper};
class HttpInitializer(credentials: GoogleCredential) extends HttpRequestInitializer {
def initialize(request: HttpRequest) = {
request.setReadTimeout(2 * 60 * 1000)
request.setInterceptor(credentials)
val backoff = new HttpBackOffUnsuccessfulResponseHandler(
new ExponentialBackOff())
.setSleeper(Sleeper.DEFAULT);
request.setUnsuccessfulResponseHandler(
new HttpUnsuccessfulResponseHandler() {
def handleResponse(request: HttpRequest, response: HttpResponse,
supportsRetry: Boolean): Boolean = {
if (credentials.handleResponse(
request, response, supportsRetry)) {
true
} else if (backoff.handleResponse(request, response, supportsRetry)) {
true
} else {
false
}
}
}
)
request.setIOExceptionHandler(
new HttpBackOffIOExceptionHandler(new ExponentialBackOff())
.setSleeper(Sleeper.DEFAULT))
}
}
示例2: Googlemonitoringapiworks
//设置package包名称以及导入依赖的类
package com.berkgokden
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.monitoring.v3.{Monitoring, MonitoringScopes}
object Googlemonitoringapiworks extends App {
println("Hello, google-monitoring-api-works")
val project = "your-project-name" // you should have one on google.
val projectResource = "projects/" + project
// Grab the Application Default Credentials from the environment.
// Download authentication json form Google Cloud and Put conf.json into resources folder!
val resourceAsStream = getClass.getResourceAsStream("/conf.json")
println("ok")
val credential = GoogleCredential.fromStream(resourceAsStream)
.createScoped(MonitoringScopes.all())
println(credential.getServiceAccountId) // this only works if you have a service account
// Create and return the CloudMonitoring service object
val httpTransport = new NetHttpTransport()
val jsonFactory = new JacksonFactory()
val service = new Monitoring.Builder(httpTransport,
jsonFactory, credential)
.setApplicationName("Monitoring Sample")
.build()
val res = service.projects().metricDescriptors().list(projectResource).execute()
println(res.toPrettyString)
}
示例3: Helper
//设置package包名称以及导入依赖的类
package io.taig.sbt.googleplay
import java.io.File
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.androidpublisher.{ AndroidPublisher, AndroidPublisherScopes }
import scala.collection.JavaConversions._
object Helper {
lazy val HttpTransport = GoogleNetHttpTransport.newTrustedTransport
lazy val JsonFactory = JacksonFactory.getDefaultInstance
def authorize( applicationName: String, serviceAccount: String, serviceAccountPrivateKey: File ): AndroidPublisher = {
val credentials = new GoogleCredential.Builder()
.setTransport( HttpTransport )
.setJsonFactory( JsonFactory )
.setServiceAccountId( serviceAccount )
.setServiceAccountScopes( List( AndroidPublisherScopes.ANDROIDPUBLISHER ) )
.setServiceAccountPrivateKeyFromP12File( serviceAccountPrivateKey )
.build
new AndroidPublisher.Builder( HttpTransport, JsonFactory, credentials )
.setApplicationName( applicationName )
.build
}
}
示例4: Hello
//设置package包名称以及导入依赖的类
package com.ru.waka
import java.io.File
import java.net.URL
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.gdata.client.spreadsheet.SpreadsheetService
import com.google.gdata.data.Feed
import com.google.gdata.data.docs.SpreadsheetEntry
import com.google.gdata.data.spreadsheet.SpreadsheetFeed
import scala.collection.JavaConverters._
object Hello {
private val jsonFactory = new JacksonFactory
private val transport = GoogleNetHttpTransport.newTrustedTransport()
private val service = new SpreadsheetService(this.getClass.getName)
private val scopes = Seq(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://docs.google.com/feeds",
"https://spreadsheets.google.com/feeds"
).asJava
def main (args: Array[String] ) {
val c = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("[email protected]")
.setServiceAccountPrivateKeyFromP12File(new File("./hubot-dark-6e8b3857b0b0.p12"))
.setServiceAccountScopes(scopes)
.build()
c.refreshToken()
service.setOAuth2Credentials(c)
val e = service.getFeed(new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full"), classOf[SpreadsheetFeed])
println(e.getAuthors)
println(e.getTitle.getPlainText)
}
}
示例5: DefaultSource
//设置package包名称以及导入依赖的类
package com.logicstack.spark
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.sources.{BaseRelation, RelationProvider, SchemaRelationProvider}
import org.apache.spark.sql.types.StructType
class DefaultSource extends SchemaRelationProvider {
private val httpTransport = GoogleNetHttpTransport.newTrustedTransport
private val jsonFactory = JacksonFactory.getDefaultInstance
override def createRelation(sqlContext: SQLContext, parameters: Map[String, String], schema: StructType): ReportRelation = {
val clientId = parameters("clientId")
val clientSecret = parameters("clientSecret")
val accessToken = parameters("accessToken")
val refreshToken = parameters("refreshToken")
val credential = new GoogleCredential.Builder()
.setJsonFactory(jsonFactory)
.setTransport(httpTransport)
.setClientSecrets(clientId, clientSecret)
.build()
.setAccessToken(accessToken)
.setRefreshToken(refreshToken)
val analyticsReporting = new AnalyticsReporting.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("spark-ga")
.build()
new ReportRelation(
analyticsReporting,
parameters("profile"),
parameters("startDate"),
parameters("endDate"),
schema
)(sqlContext)
}
}
示例6: googleAuthConfig
//设置package包名称以及导入依赖的类
package components
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import com.gu.googleauth.{GoogleAuthConfig, GoogleGroupChecker, GoogleServiceAccount}
import controllers.GroupsAuthConfig
import play.api.Logger
import scala.collection.JavaConverters._
trait GoogleAuthComponents { self: ConfigUtil =>
def googleAuthConfig = GoogleAuthConfig(
clientId = mandatoryConfig("google.clientId"),
clientSecret = mandatoryConfig("google.clientSecret"),
redirectUrl = mandatoryConfig("google.redirectUrl"),
domain = "ovoenergy.com"
)
def groupsAuthConfig: Option[GroupsAuthConfig] = {
if (configuration.getBoolean("google.groupsAuthorisation.enabled").getOrElse(false)) {
val acceptedGroups = configuration
.getStringList("google.groupsAuthorisation.acceptedGroups")
.map(_.asScala.toSet)
.getOrElse(Set.empty)
val serviceAccount = {
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
val credentials: GoogleCredential = {
val json = mandatoryConfig("google.groupsAuthorisation.serviceAccountCreds")
GoogleCredential.fromStream(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))
}
GoogleServiceAccount(
email = credentials.getServiceAccountId,
privateKey = credentials.getServiceAccountPrivateKey,
impersonatedUser = mandatoryConfig("google.groupsAuthorisation.impersonatedUser")
)
}
val groupChecker = new GoogleGroupChecker(serviceAccount)
Logger.info("Google Groups authorisation is ENABLED")
Some(GroupsAuthConfig(acceptedGroups, groupChecker))
} else {
Logger.info("Google Groups authorisation is DISABLED")
None
}
}
}
示例7: OcrTest
//设置package包名称以及导入依赖的类
import java.io.FileInputStream
import java.io.File
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.vision.v1.model._
import com.google.api.services.vision.v1.{Vision, VisionScopes}
import com.google.common.collect.ImmutableList
import java.nio.file.{Files}
import ocr.model.OcrTextAnnotation
object OcrTest {
def main2(args: Array[String]): Unit = {
val credential =
GoogleCredential
.fromStream(new FileInputStream(new File("/home/leonti/development/google-cloud/Receipts-dev-ocr-service-account.json")))
.createScoped(VisionScopes.all())
val jsonFactory = JacksonFactory.getDefaultInstance
val vision = new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
.setApplicationName("Receipts")
.build()
val requests: ImmutableList.Builder[AnnotateImageRequest] = ImmutableList.builder()
requests.add(
new AnnotateImageRequest()
.setImage(
new Image().encodeContent(Files.readAllBytes(new File("/home/leonti/development/document-scanner/images/7.jpg").toPath)))
.setFeatures(ImmutableList.of(new Feature()
.setType("TEXT_DETECTION")
.setMaxResults(100))))
val annotate =
vision
.images()
.annotate(new BatchAnnotateImagesRequest().setRequests(requests.build()))
// Due to a bug: requests to Vision API containing large images fail when GZipped.
annotate.setDisableGZipContent(true)
val batchResponse = annotate.execute()
val response = batchResponse.getResponses().get(0)
val annotations = response.getTextAnnotations
println(response.getFullTextAnnotation.toPrettyString)
val fullAnnotation = OcrTextAnnotation.fromTextAnnotation(response.getFullTextAnnotation)
println(fullAnnotation)
}
}
示例8: BigQueryClient
//设置package包名称以及导入依赖的类
package com.example.prodspark.client
import java.io.IOException
import com.example.prodspark.util.RetryUtil
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.bigquery.{Bigquery, BigqueryScopes}
import com.google.api.services.bigquery.model._
import com.google.cloud.hadoop.io.bigquery.BigQueryStrings
import org.slf4j.LoggerFactory
import scala.collection.JavaConverters._
object BigQueryClient {
private val SCOPES = List(BigqueryScopes.BIGQUERY).asJava
private val bigquery: Bigquery = {
val credential = GoogleCredential.getApplicationDefault.createScoped(SCOPES)
new Bigquery.Builder(new NetHttpTransport, new JacksonFactory, credential)
.setApplicationName("spark-bigquery")
.build()
}
def streamingInsert(
rows: Seq[TableDataInsertAllRequest.Rows],
tableSpec: String,
projectId: String
): Unit = {
lazy val tableRef = BigQueryStrings.parseTableReference(tableSpec)
val req = new TableDataInsertAllRequest()
.setRows(rows.asJava)
.setIgnoreUnknownValues(true)
RetryUtil.retry(3) {
val response = insertAll(tableRef, req)
if (response.getInsertErrors != null) {
log.error("Error inserting into BigQuery: " + response.getInsertErrors.toString)
throw new IOException(response.getInsertErrors.toString)
}
}
}
private val log = LoggerFactory.getLogger(this.getClass)
}
示例9: FilePathCredentials
//设置package包名称以及导入依赖的类
package mn.clarkson.google
import java.io.FileInputStream
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.services.pubsub.model.PubsubMessage
package object pubsub extends {
implicit class FilePathCredentials(path: String) extends Credentials {
def build(): GoogleCredential = {
GoogleCredential.fromStream(new FileInputStream(path))
}
}
implicit class DefaultCredentials(unit: Unit) extends Credentials {
def build(): GoogleCredential = GoogleCredential.getApplicationDefault
}
implicit class IdentityCredentials(credentials: GoogleCredential) extends Credentials {
def build(): GoogleCredential = credentials
}
implicit class ByteMessage(data: Array[Byte]) extends Messages {
def toMessage: Seq[PubsubMessage] = Seq(new PubsubMessage().encodeData(data))
}
implicit class ByteMessages(data: Seq[Array[Byte]]) extends Messages {
def toMessage: Seq[PubsubMessage] = data.map(new PubsubMessage().encodeData)
}
implicit class StringMessage(data: String) extends Messages {
def toMessage: Seq[PubsubMessage] = Seq(new PubsubMessage().encodeData(data.getBytes))
}
implicit class StringMessages(data: Seq[String]) extends Messages {
def toMessage: Seq[PubsubMessage] = data.map(_.getBytes).map(new PubsubMessage().encodeData)
}
implicit class PubSubMessage(data: PubsubMessage) extends Messages {
def toMessage: Seq[PubsubMessage] = Seq(data)
}
implicit class PubSubMessages(data: Seq[PubsubMessage]) extends Messages {
def toMessage: Seq[PubsubMessage] = data
}
}
示例10: GoogleContainerEngine
//设置package包名称以及导入依赖的类
package io.incube.blue
import java.io.ByteArrayInputStream
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.{HttpRequest, HttpRequestInitializer}
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.container.{Container, ContainerScopes}
object GoogleContainerEngine {
val jsonFactory = JacksonFactory.getDefaultInstance
val httpTransport = GoogleNetHttpTransport.newTrustedTransport() //TODO: handle exceptions
//TODO: abstract this away
val serviceAccount = new ByteArrayInputStream("{\n \"type\": \"service_account\",\n \"project_id\": \"gcp-client-0\",\n \"private_key_id\": \"5b5a03aab0c47c9d200fe660b716341a38030b93\",\n \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC1kmgkZowaxW0t\\nP3httySW6Fc3qCIboJhpaoCPnesPrWQhNR7cpJjauwxqzr6Di7O7fbRC7Y4e9Bjv\\nclD1vK2U842ZLREkMaFG7RMi2lMtmzJlsYyEP/BEHe/YxqjrxtlaH9KeVCwTpzWl\\nttpaXxNsF2jc6EQT/vuYBS2ru9tJGrfh+i+6ILlPMQhXw/tcea7phbGPAWI4ZFcY\\nMpAtn0Jf4h6GNs6CfrMzOQqwY8OEmDqZZDmN1uwYTzbEokYcSx+Emji/3h7KEKGk\\nZ/72/zHQDkK43JtrrIvz1yuzsgmct1qA3RuygQujf7GDZ8TkAPAxp+/Q//nw9VQw\\nHOSBVepHAgMBAAECggEBAKAEaE10JpNNXLtczWh71/46wuqk/XI1pTx6BNUNCmTl\\nnXH6m7k+Qgu6fuX+UD4kN4DL9rppGzBCVVto9tqqrpuvzSGqawnnx0d3lb7IhDeU\\nJ+UhhUHkC34sl/0Gj0ZDF7hqhTbN3Y5wdUIXFPZCBh7jvqG4/I5W0CoYnjhUNZyF\\nOHe1wvOTph5/pddZkurs+0XWeC1y68AqryoOlWc8T54SiHOeuEssVsJLKiP9+1a5\\n7DKKQYyFZHdf/ftbIOUnbG9decFlUQGN1T23S/pOKCEHde9nEc6f1U/Uuer0KLz+\\niJuz2gCNTdaOG1BSKcrijiiVxClDcl8snT+rEbvfgekCgYEA16ottqNlPV2/sg2D\\nTlxdyBYWwDjooKTxb9mf6FwDMzHhZ7WekRqBjuATgXoItWKJaIg3cAtNFmeUSofk\\nuoV/l9VsL3lt6M1wvhjXcODAwLztcNsh5XPl96iaxdp+uE4F0LrTHHHwJPzhHYiW\\nbG2JUA7HX05FSuGWTCUKwhf6zIsCgYEA14flGurU4gh5bLRbbafCVyf1rXkHGMO8\\nzXisZGmGk4dC1FDiXfnGe3d4XbZhKDgCnl2vNGEuQxz2RmYbb1X+EvagH+31jEJH\\npVWjXgmTXALk7y2OYb7W0vyZ6JUYy7O11bwAjHBc/wwV2V3TZbFye9ov0PdIzgNO\\nb02BkRH3ZLUCgYAGziPrI3TKXu7xm2ONUXTUH35QSntstke4E9Hr7xtavjQypZR/\\nV6rG62MyLrufnaBgYAv/yRuBnXscbvVUvWmtTNrBFL/XHMR1+yqxMSZj7pI/gWqs\\nZt/W1MctfxuIjU25rGuE9kNxp1kjKXA1s68li5HW/A1Ls5qehHy2azNKyQKBgQCy\\nBfljBlzYZo+FDmQGau7G9qaiprkJ54NnZClgtxkFek/k9vpDDTC4grHVFfOiOMFQ\\n9ajl5u9DWATDmUtH5wt5tmQEe5S6SXTMR7Qs1FP3SBy4wjQ84Fio5SRrS9uzRbkH\\n1cXOOnFV6TGS3UDjWnJpgorEW7yzDWAX5zkCDoj9kQKBgHPzaKbywanRmNtEKH8k\\nL7F2Xux8TstRv/kFqiGSIWuxRVP/0zcKRCpGtQsceYcJGbCwD15D8oOnA9FcVYw8\\nM+pHf+eXZJldJHX8Kiegmv1ZsDd9a2rKiZGNlmnh9wjc/lsHrcCu539TNu/beXNH\\naJUIF4V+GHDuPhQciDmEhM3y\\n-----END PRIVATE KEY-----\\n\",\n \"client_email\": \"[email protected]\",\n \"client_id\": \"100218978202688694903\",\n \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\": \"https://accounts.google.com/o/oauth2/token\",\n \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/postman%40gcp-client-0.iam.gserviceaccount.com\"\n}".getBytes)
final private val container = new Container(httpTransport, jsonFactory, new HttpRequestInitializer {
override def initialize(request: HttpRequest): Unit = {
GoogleCredential.fromStream(serviceAccount).createScoped(ContainerScopes.all).initialize(request)
}
})
def instance = container
}