当前位置: 首页>>代码示例>>Scala>>正文


Scala ObjectMetadata类代码示例

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


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

示例1: S3FileDetails

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

import java.io.ByteArrayInputStream
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{AmazonS3Exception, ListObjectsV2Request, ObjectMetadata}
import org.apache.commons.compress.utils.IOUtils

import scala.collection.JavaConverters._
import play.api.Logger

case class S3FileDetails(contents: Array[Byte], key: String, bucket: String)

class AmazonS3ClientWrapper(client: AmazonS3Client) {

  def uploadFile(fileDetails: S3FileDetails): Either[String, String] = {
    val stream = new ByteArrayInputStream(fileDetails.contents)
    try {
      val meta = new ObjectMetadata()
      meta.setContentLength(fileDetails.contents.length)
      client.putObject(fileDetails.bucket, fileDetails.key, stream, meta)
      Logger.info(s"Uploaded file to S3: ${fileDetails.bucket} - ${fileDetails.key}")
      Right(client.getResourceUrl(fileDetails.bucket, fileDetails.key))
    } catch {
      case e: AmazonS3Exception =>
        Left(s"Failed to upload to aws.s3 with error: ${e.getMessage} for file: ${fileDetails.key} ")
    } finally {
      IOUtils.closeQuietly(stream)
    }
  }

  def downloadFile(bucket: String, key: String): Either[String, Array[Byte]] = {
    try {
      val obj    = client.getObject(bucket, key)
      val stream = obj.getObjectContent
      try {
        Right(IOUtils.toByteArray(stream))
      } finally {
        stream.close()
      }
    } catch {
      case e: AmazonS3Exception =>
        // either the object does not exist or something went really wrong
        Logger.warn(s"Failed to download aws.s3://$bucket/$key", e)
        Left(s"Failed to download s3://$bucket/$key, with status code ${e.getStatusCode}")

    }
  }

  // Returns keys of all the files in specified s3 bucket with the given prefix
  def listFiles(bucket: String, prefix: String): Either[String, Seq[String]] = {
    try {
      val request = new ListObjectsV2Request().withBucketName(bucket).withPrefix(prefix)
      val result  = client.listObjectsV2(request).getObjectSummaries.asScala.map(_.getKey)
      Right(result)
    } catch {
      case e: AmazonS3Exception =>
        Logger.warn(s"Failed to list objects under s3://$bucket/$prefix", e)
        Left(s"Failed to retrieve template files from s3://$bucket/$prefix")
    }
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:62,代码来源:AmazonS3ClientWrapper.scala

示例2: FileUploadService

//设置package包名称以及导入依赖的类
package ylabs.play.common.services

import java.io.InputStream
import java.net.URI
import java.time.Instant
import java.util.{Date, UUID}

import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.ObjectMetadata
import com.typesafe.config.ConfigFactory
import ylabs.play.common.models.FileUpload.FileDescription

import scala.concurrent.{ExecutionContext, Future}

object FileUploadService {
  val expirationYears:Long = 20
  val binExpirationTime: Long = expirationYears*365L*24L*60L*60L*1000L
}

class FileUploadService {
  lazy val s3 = new AmazonS3Client
  lazy val config = ConfigFactory.load()
  lazy val bucketName = config.getString("aws.s3.bucket")
  def upload(file: InputStream, description: Option[FileDescription])(implicit ec: ExecutionContext): Future[URI] = {
    Future {
      if (!s3.doesBucketExist(bucketName)) s3.createBucket(bucketName)

      val metadata = new ObjectMetadata
      metadata.addUserMetadata("Description", description.getOrElse(FileDescription("None")).value)
      val id = UUID.randomUUID().toString
      val putObj = s3.putObject(bucketName, id, file, metadata)
      val expireDate = Date.from(Instant.ofEpochMilli(new Date().getTime + FileUploadService.binExpirationTime))
      s3.generatePresignedUrl(bucketName, id, expireDate).toURI
    }
  }
} 
开发者ID:springnz,项目名称:play-app-base,代码行数:37,代码来源:FileUploadService.scala

示例3: encrypt

//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.aws.s3

import com.amazonaws.services.s3.model.{ObjectMetadata, PutObjectRequest, SSEAlgorithm, SSEAwsKeyManagementParams}

trait Encryption {
  def encrypt(request: PutObjectRequest): PutObjectRequest
}

trait EncryptByAlgorithm {
  this: Encryption =>

  def encrypt(request: PutObjectRequest, algorithm: String, secret: String): PutObjectRequest = {
    val objectMetadata = new ObjectMetadata()
    objectMetadata.setSSEAlgorithm(algorithm)

    request.withMetadata(objectMetadata).withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(secret))
  }
}

case class AES256(secret: String) extends Encryption with EncryptByAlgorithm {
  override def encrypt(request: PutObjectRequest): PutObjectRequest =
    encrypt(request, SSEAlgorithm.AES256.getAlgorithm, secret)
}

case class KMS(secret: String) extends Encryption with EncryptByAlgorithm  {
  override def encrypt(request: PutObjectRequest): PutObjectRequest =
    encrypt(request, SSEAlgorithm.KMS.getAlgorithm, secret)
} 
开发者ID:UKHomeOffice,项目名称:aws-scala-lib,代码行数:29,代码来源:Encryption.scala

示例4: S3

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

import java.io.File
import java.nio.file.{Files, StandardCopyOption}

import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{CannedAccessControlList, ObjectMetadata, PutObjectRequest}
import com.typesafe.config.ConfigFactory
import org.im4java.core.{ConvertCmd, IMOperation}

class S3 {
  def handler(event: S3Event, context: Context): String = {
    val config = ConfigFactory.load()
    val record = event.getRecords.get(0)

    val bucket = record.getS3.getBucket.getName
    val key = record.getS3.getObject.getKey

    val pattern = """(.+)\.(.+)""".r
    val patternThumbnail = """(.+)_thumbnail\.(.+)""".r

    key match {
      case patternThumbnail(name, format) => {

      }
      case pattern(name, format) => {
        val client = new AmazonS3Client()
        val s3Object = client.getObject(bucket, key)

        val inMetadata = s3Object.getObjectMetadata
        val input = s3Object.getObjectContent
        val inputFile = File.createTempFile("s3handler", "input")
        Files.copy(input, inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING)

        val resizedImage = File.createTempFile("s3handler", "resizedImage")

        val op = new IMOperation()
        op.addImage(inputFile.getAbsolutePath)
        op.resize(config.getInt("resized.width"), config.getInt("resized.height"))
        op.addImage(resizedImage.getAbsolutePath)

        val converter = new ConvertCmd()
        converter.run(op)

        val resizedKey = name + "_thumbnail." + format

        val putObjectRequest = new PutObjectRequest(bucket, resizedKey, resizedImage)
        val resizedImageMetadata = new ObjectMetadata()
        resizedImageMetadata.setContentType(inMetadata.getContentType)
        putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead).withMetadata(resizedImageMetadata)

        client.putObject(putObjectRequest)
      }
    }

    key
  }
} 
开发者ID:phji,项目名称:lambda-resize-s3-image,代码行数:61,代码来源:S3.scala


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