public static void AsyncCopyObject(string sourceBucket, string sourceKey, string targetBucket, string targetKey)
        {
            try
            {
                var metadata = new ObjectMetadata();
                metadata.AddHeader("mk1", "mv1");
                metadata.AddHeader("mk2", "mv2");
                var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
                {
                    NewObjectMetadata = metadata
                };
                client.BeginCopyObject(req, CopyObjectCallback, null);

                _event.WaitOne();
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
예제 #2
0
파일: S3Storage.cs 프로젝트: zzms/Foundatio
        public async Task <bool> CopyFileAsync(string path, string targetpath, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var client = CreateClient()) {
                var req = new CopyObjectRequest {
                    SourceBucket      = _bucket,
                    SourceKey         = path.Replace('\\', '/'),
                    DestinationBucket = _bucket,
                    DestinationKey    = targetpath.Replace('\\', '/')
                };

                var res = await client.CopyObjectAsync(req, cancellationToken).AnyContext();

                return(res.HttpStatusCode.IsSuccessful());
            }
        }
예제 #3
0
        public void CopyToBucket(Guid guid, string bucketName)
        {
            var source      = String.Format("{0}/{1}.jpg", Folders.PhotoBackups, guid);
            var destination = String.Format("{0}/{1}.jpg", Folders.DeletedPhotos, guid);

            using (var client = CreateAmazonS3Client()) {
                var request = new CopyObjectRequest {
                    SourceBucket      = _bucket.BucketName,
                    SourceKey         = source,
                    DestinationBucket = String.IsNullOrWhiteSpace(bucketName) ? _bucket.BucketName : bucketName,
                    DestinationKey    = destination
                };
                client.CopyObject(request);
            }
        }
예제 #4
0
        public CopyObjectResponse CopyObject(CopyObjectRequest request)
        {
            var s3CopyObjectRequest = new Amazon.S3.Model.CopyObjectRequest()
            {
                SourceBucket      = request.SourceBucket,
                SourceKey         = request.SourceKey,
                DestinationBucket = request.Bucket,
                DestinationKey    = request.Key,
            };


            var result = _amazonS3Client.CopyObjectAsync(s3CopyObjectRequest).Result;

            return(null);
        }
예제 #5
0
 private void SimpleCopy()
 {
     copyObjectRequest = new CopyObjectRequest(bucket, key);
     copyObjectRequest.SetCopyMetaDataDirective(Common.CosMetaDataDirective.COPY);
     copyObjectRequest.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
     copyObjectRequest.SetCopySource(copySource);
     cosXmlServer.CopyObject(copyObjectRequest, delegate(CosResult cosResult)
     {
         lock (syncExit)
         {
             if (isExit)
             {
                 if (taskState == TaskState.CANCEL)
                 {
                     DeleteObject();
                 }
                 return;
             }
         }
         if (UpdateTaskState(TaskState.COMPLETED))
         {
             CopyObjectResult result       = cosResult as CopyObjectResult;
             CopyTaskResult copyTaskResult = new CopyTaskResult();
             copyTaskResult.SetResult(result);
             if (successCallback != null)
             {
                 successCallback(copyTaskResult);
             }
         }
     },
                             delegate(CosClientException clientEx, CosServerException serverEx)
     {
         lock (syncExit)
         {
             if (isExit)
             {
                 return;
             }
         }
         if (UpdateTaskState(TaskState.FAILED))
         {
             if (failCallback != null)
             {
                 failCallback(clientEx, serverEx);
             }
         }
     });
 }
        /// <summary>
        /// Sets the properties, like cacheControl, content type, etc.
        /// </summary>
        /// <param name="location">Descriptor of the item on the remote blob storage.</param>
        /// <param name="properties">The properties to set.</param>
        public override void SetProperties(IBlobContentLocation location, IBlobProperties properties)
        {
            //No properties to set by default
            var req = new CopyObjectRequest()
                      .WithDirective(S3MetadataDirective.REPLACE)
                      .WithSourceBucket(this.bucketName)
                      .WithSourceKey(location.FilePath)
                      .WithDestinationBucket(this.bucketName)
                      .WithDestinationKey(location.FilePath);

            req.AddHeader("x-amz-acl", "public-read");
            req.AddHeader("Cache-Control", properties.CacheControl);
            req.AddHeader("Content-Type", properties.ContentType);

            transferUtility.S3Client.CopyObject(req);
        }
        public async Task CopyObjectInBucketAsyncTest()
        {
            IAmazonS3 client = CreateMockS3Client();

            var request = new CopyObjectRequest
            {
                SourceBucket      = newBucket,
                SourceKey         = keyName,
                DestinationBucket = newBucket,
                DestinationKey    = $"{destinationFolderName}\\{keyName}",
            };

            var response = await client.CopyObjectAsync(request);

            Assert.True(response.HttpStatusCode == System.Net.HttpStatusCode.OK, $"Could not copy {keyName}.");
        }
예제 #8
0
        public async Task <bool> CopyObject(string sourceBucket, string sourceKey, string destinationBucket, string destinationKey, CancellationToken cancellationToken = default)
        {
            var request = new CopyObjectRequest()
            {
                SourceBucket      = sourceBucket,
                SourceKey         = sourceKey,
                DestinationBucket = destinationBucket,
                DestinationKey    = destinationKey,
            };

            var policy = base.CreateDefaultRetryAsyncPolicy();

            var response = await policy.ExecuteAsync(async() => await S3Client.CopyObjectAsync(request, cancellationToken));

            return(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
예제 #9
0
        public override bool CreateFromAlternateCopy(string file, string source)
        {
            file   = file.Replace('\\', '/');
            source = source.Replace('\\', '/');
            CopyObjectRequest request = new CopyObjectRequest()
            {
                SourceBucket      = this.bucket,
                DestinationBucket = this.bucket,
                SourceKey         = this.prefix + source,
                DestinationKey    = this.prefix + file
            };

            this.withHandling(() => this.client.CopyObject(request), file);
            this.files.Add(file);
            return(true);
        }
예제 #10
0
        public void CopyFile(string fromVirtualPath, string destinationVirtualPath)
        {
            var copyRequest = new CopyObjectRequest()
                              .WithMetaData("Expires", DateTime.Now.AddYears(10).ToString("R"))
                              .WithSourceBucket(this.bucketName)
                              .WithSourceKey(fromVirtualPath)
                              .WithDestinationBucket(this.bucketName)
                              .WithDestinationKey(destinationVirtualPath)
                              .WithCannedACL(S3CannedACL.PublicRead);

            using (this.s3.CopyObject(copyRequest)) { }
            if (FileCopied != null)
            {
                FileCopied.Invoke(this, new FileEventArgs(FixPathForN2(fromVirtualPath), FixPathForN2(destinationVirtualPath)));
            }
        }
예제 #11
0
        private static void RenameS3Object(string oldKey, string newKey)
        {
            // Copy
            CopyObjectRequest request = new CopyObjectRequest
            {
                SourceBucket      = BucketName,
                SourceKey         = oldKey,
                DestinationBucket = BucketName,
                DestinationKey    = newKey
            };

            _amazonS3Client.CopyObject(request);

            // Delete
            DeleteS3Object(oldKey);
        }
예제 #12
0
파일: UnitTestKs3.cs 프로젝트: jflzbest/C-
        public void TestCopyObject()
        {
            if (init())
            {
                CopyObjectRequest copyObjectRequest = new CopyObjectRequest();
                copyObjectRequest.SourceObject      = objKeyNameFileData;
                copyObjectRequest.SourceBucket      = bucketName;
                copyObjectRequest.DestinationBucket = "test2-zzy-jr";
                copyObjectRequest.DestinationObject = objKeyNameFileData;
                //CannedAccessControlList cannedAcl=new CannedAccessControlList(CannedAccessControlList.PUBLICK_READ_WRITE);
                //copyObjectRequest.CannedAcl = cannedAcl;

                CopyObjectResult result = ks3Client.copyObject(copyObjectRequest);
                Assert.IsNotNull(result);
            }
        }
예제 #13
0
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="S3Manager"></param>
        /// <param name="bucketName1"></param>
        /// <param name="bucketName2"></param>
        /// <param name="fileName1"></param>
        /// <param name="fileName2"></param>
        /// <returns></returns>
        public static ActionResult Move(IAmazonS3 S3Manager, string bucketName1, string fileName1, string bucketName2, string fileName2)
        {
            ActionResult ar = new ActionResult()
            {
                IsSuccess = false,
                Msg       = "Empty"
            };

            if (S3Manager != null)
            {
                ListObjectsRequest request = new ListObjectsRequest();
                request.BucketName = bucketName1;
                request.Prefix     = fileName1;

                ListObjectsResponse response = S3Manager.ListObjects(request);
                if (response.S3Objects.Count == 1)
                {
                    CopyObjectRequest copyObjectRequest = new CopyObjectRequest();
                    copyObjectRequest.SourceBucket      = bucketName1;
                    copyObjectRequest.SourceKey         = fileName1;
                    copyObjectRequest.DestinationBucket = bucketName2;
                    copyObjectRequest.DestinationKey    = fileName2;
                    CopyObjectResponse res = S3Manager.CopyObject(copyObjectRequest);
                    if (res.HttpStatusCode == HttpStatusCode.OK)
                    {
                        S3Manager.DeleteObject(bucketName1, fileName1);

                        ar.IsSuccess = true;
                        ar.Msg       = "移动成功!";
                    }
                    else
                    {
                        ar.IsSuccess = false;
                        ar.Msg       = "复制失败!";
                    }
                }
                else
                {
                    ar.IsSuccess = false;
                    ar.Msg       = "文件不存在!";
                }
            }



            return(ar);
        }
예제 #14
0
        public async Task CopyBlobAsync(string sourceContainerName, string sourceBlobName,
                                        string destinationContainerName, string destinationBlobName = null)
        {
            if (string.IsNullOrEmpty(sourceContainerName))
            {
                throw new StorageException(StorageErrorCode.InvalidName, $"Invalid {nameof(sourceContainerName)}");
            }
            if (string.IsNullOrEmpty(sourceBlobName))
            {
                throw new StorageException(StorageErrorCode.InvalidName, $"Invalid {nameof(sourceBlobName)}");
            }
            if (string.IsNullOrEmpty(destinationContainerName))
            {
                throw new StorageException(StorageErrorCode.InvalidName, $"Invalid {nameof(destinationContainerName)}");
            }
            if (destinationBlobName == string.Empty)
            {
                throw new StorageException(StorageErrorCode.InvalidName, $"Invalid {nameof(destinationBlobName)}");
            }

            var sourceKey      = GenerateKeyName(sourceContainerName, sourceBlobName);
            var destinationKey = GenerateKeyName(destinationContainerName, destinationBlobName ?? sourceBlobName);

            try
            {
                var request = new CopyObjectRequest
                {
                    SourceBucket               = _bucket,
                    SourceKey                  = sourceKey,
                    DestinationBucket          = _bucket,
                    DestinationKey             = destinationKey,
                    ServerSideEncryptionMethod = _serverSideEncryptionMethod
                };

                var response = await _s3Client.CopyObjectAsync(request);

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new StorageException(StorageErrorCode.GenericException, "Copy failed.");
                }
            }
            catch (AmazonS3Exception asex)
            {
                throw asex.ToStorageException();
            }
        }
예제 #15
0
        public static void Copy()
        {
            using (client = new AmazonS3Client("AKIAI4YXWZLJGJQBSZ6Q", "FctcgO3mUeaTt+oXOj5WxQWXSzTkOWiuMav26dz5", Amazon.RegionEndpoint.APSoutheast1))
            {
                var copyObjectRequest = new CopyObjectRequest
                {
                    SourceBucket      = bucketName + "/temp",
                    SourceKey         = "17d8d41345aa4185b591ba5f55ef53fc.png",
                    DestinationBucket = bucketName + "/store",
                    DestinationKey    = "17d8d41345aa4185b591ba5f55ef53fc.png",
                };

                client.CopyObjectAsync(copyObjectRequest).Wait();

                Console.WriteLine("Copy successfull");
            }
        }
예제 #16
0
        private async Task UpdateReadTimeAsync(ObjectIdentity identity, IAmazonS3 s3Client)
        {
            var metadataCollection = await GetObjectMetadataAsync(s3Client, identity, false);

            metadataCollection[MetadataKeys.ReadTime] = RebusTime.Now.ToString("O");
            var copyObjectRequest = new CopyObjectRequest
            {
                SourceBucket      = _options.BucketName,
                DestinationBucket = _options.BucketName,
                SourceKey         = identity.Key,
                DestinationKey    = identity.Key,
                MetadataDirective = S3MetadataDirective.REPLACE
            };

            metadataCollection.SaveTo(copyObjectRequest.Metadata);
            await s3Client.CopyObjectAsync(copyObjectRequest);
        }
        public static void SetObjectStorageClass(string bucketName, string key, S3StorageClass sClass, AmazonS3 s3Client)
        {
            if ((sClass > S3StorageClass.ReducedRedundancy) || (sClass < S3StorageClass.Standard))
            {
                throw new ArgumentException("Invalid value specified for storage class.");
            }
            if (s3Client == null)
            {
                throw new ArgumentNullException("s3Client", "Please specify an S3 Client to make service requests.");
            }
            CopyObjectRequest request = new CopyObjectRequest();

            request.SourceBucket = request.DestinationBucket = bucketName;
            request.SourceKey    = request.DestinationKey = key;
            request.StorageClass = sClass;
            s3Client.CopyObject(request);
        }
예제 #18
0
        /// <summary>
        /// Copies this file to the location indicated by the passed in S3FileInfo.
        /// If the file already exists in S3 and overwrite is set to false than an ArgumentException is thrown.
        /// </summary>
        /// <param name="file">The target location to copy this file to.</param>
        /// <param name="overwrite">Determines whether the file can be overwritten.</param>
        /// <exception cref="T:System.IO.IOException">If the file already exists in S3 and overwrite is set to false.</exception>
        /// <exception cref="T:System.Net.WebException"></exception>
        /// <exception cref="T:Amazon.S3.AmazonS3Exception"></exception>
        /// <returns>S3FileInfo of the newly copied file.</returns>
        public S3FileInfo CopyTo(S3FileInfo file, bool overwrite)
        {
            if (!overwrite)
            {
                if (file.Exists)
                {
                    throw new IOException("File already exists");
                }
            }

            if (SameClient(file))
            {
                var request = new CopyObjectRequest
                {
                    DestinationBucket = file.BucketName,
                    DestinationKey    = S3Helper.EncodeKey(file.ObjectKey),
                    SourceBucket      = bucket,
                    SourceKey         = S3Helper.EncodeKey(key)
                };
                ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)request).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler);
                s3Client.CopyObject(request);
            }
            else
            {
                var getObjectRequest = new GetObjectRequest
                {
                    BucketName = bucket,
                    Key        = S3Helper.EncodeKey(key)
                };
                ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)getObjectRequest).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler);
                var getObjectResponse = s3Client.GetObject(getObjectRequest);
                using (Stream stream = getObjectResponse.ResponseStream)
                {
                    var putObjectRequest = new PutObjectRequest
                    {
                        BucketName  = file.BucketName,
                        Key         = S3Helper.EncodeKey(file.ObjectKey),
                        InputStream = stream
                    };
                    ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)putObjectRequest).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler);
                    file.S3Client.PutObject(putObjectRequest);
                }
            }

            return(file);
        }
예제 #19
0
        private async Task <bool> ImportS3Object(string sourceBucket, string key, bool replace = false)
        {
            // check if target object already exists
            var found = false;

            try {
                var existing = await Settings.S3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest {
                    BucketName   = Settings.DeploymentBucketName,
                    Key          = key,
                    RequestPayer = RequestPayer.Requester
                });

                found = true;

                // check if this object was uploaded locally and therefore should not be replaced
                if (existing.Metadata[AMAZON_METADATA_ORIGIN] == Settings.DeploymentBucketName)
                {
                    LogWarn($"skipping import of 's3://{sourceBucket}/{key}' because it was published locally");
                    return(false);
                }
            } catch { }
            if (!found || replace)
            {
                var request = new CopyObjectRequest {
                    SourceBucket      = sourceBucket,
                    SourceKey         = key,
                    DestinationBucket = Settings.DeploymentBucketName,
                    DestinationKey    = key,
                    MetadataDirective = Amazon.S3.S3MetadataDirective.COPY,
                    RequestPayer      = RequestPayer.Requester
                };

                // capture the origin of this object
                request.Metadata[AMAZON_METADATA_ORIGIN] = sourceBucket;
                try {
                    await Settings.S3Client.CopyObjectAsync(request);
                } catch (AmazonS3Exception e) {
                    LogError($"unable to copy 's3://{sourceBucket}/{key}' to deployment bucket", e);
                    return(false);
                }
                _changesDetected = true;
                return(true);
            }
            return(false);
        }
예제 #20
0
        /// <summary>Execute the NAnt task</summary>
        protected override void ExecuteTask()
        {
            // Ensure the configured bucket exists
            if (!BucketExists(BucketName))
            {
                Project.Log(Level.Error, "[ERROR] S3 Bucket '{0}' not found!", BucketName);
                return;
            }

            if (!BucketExists(GetTargetBucket))
            {
                Project.Log(Level.Error, "[ERROR] S3 Bucket '{0}' not found!", GetTargetBucket);
                return;
            }

            try
            {
                Project.Log(Level.Info, "Copying: \r\n" +
                            "From: " + BucketName + ": " + sourceKey + "\r\n" +
                            "to:   " + GetTargetBucket + ": " + targetKey);

                CopyObjectRequest request = new CopyObjectRequest
                {
                    SourceBucket      = BucketName,
                    SourceKey         = sourceKey,
                    DestinationBucket = GetTargetBucket,
                    DestinationKey    = targetKey
                };
                CopyObjectResponse response = Client.CopyObject(request);
            }
            catch (AmazonS3Exception ex)
            {
                Project.Log(Level.Error, "[ERROR] {0}: {1} \r\n{2}", ex.StatusCode, ex.Message, ex.InnerException);
                return;
            }

            if (!FileExists(targetKey))
            {
                Project.Log(Level.Error, "Copy FAILED!");
            }
            else
            {
                Project.Log(Level.Info, "Copy successful!");
            }
        }
        public void ResumableCopyNegativeTest()
        {
            var sourcekey = OssTestUtils.GetObjectKey(_className);
            var targetkey = OssTestUtils.GetObjectKey(_className);
            var request   = new CopyObjectRequest(_bucketName, sourcekey, _bucketName, targetkey);

            Assert.AreEqual(request.RequestPayer, RequestPayer.BucketOwner);

            try
            {
                _ossPayerClient.ResumableCopyObject(request, Config.DownloadFolder);
                Assert.Fail("should not be here.");
            }
            catch (Exception e)
            {
                Assert.IsTrue(true, e.Message);
            }
        }
예제 #22
0
        public async Task <string> DeployModelAsync(DeploymentTarget deploymentTarget, RegisteredModel registeredModel, Experiment experiment)
        {
            var deploymentPath = this.modelPathGenerator.GetDeploymentPath(deploymentTarget, experiment.ExperimentName);

            await CreateBucketAsync(this.s3Client, deploymentRepositoryBucket, isPublic : true);

            var copyObjectRequest = new CopyObjectRequest
            {
                SourceBucket      = modelRepositoryBucket,
                SourceKey         = this.modelPathGenerator.GetModelName(registeredModel.RunId),
                DestinationBucket = deploymentRepositoryBucket,
                DestinationKey    = deploymentPath
            };

            await this.s3Client.CopyObjectAsync(copyObjectRequest);

            return(GetDeploymentUri(experiment, deploymentTarget));
        }
예제 #23
0
        private CopyObjectRequest CreateUpdateRequest(string containerName, string blobName, BlobProperties properties)
        {
            var updateRequest = new CopyObjectRequest()
            {
                SourceBucket      = _bucket,
                SourceKey         = GenerateKeyName(containerName, blobName),
                DestinationBucket = _bucket,
                DestinationKey    = GenerateKeyName(containerName, blobName),
                ContentType       = properties?.ContentType,
                CannedACL         = GetCannedACL(properties),
                MetadataDirective = S3MetadataDirective.REPLACE,
            };

            updateRequest.Headers.ContentDisposition = properties.ContentDisposition;
            updateRequest.Metadata.AddMetadata(properties?.Metadata);

            return(updateRequest);
        }
예제 #24
0
        public void CanSetMetdataDirective()
        {
            var request = new CopyObjectRequest(
                host: "s3.amazon.com",
                source: new S3ObjectLocation("sourceBucket", "video.mp4"),
                target: new S3ObjectLocation("targetBucket", "video.mp4")
                );

            request.MetadataDirective = MetadataDirectiveValue.Replace;

            Assert.Equal("REPLACE", request.Headers.GetValues("x-amz-metadata-directive").First());

            Assert.Equal(MetadataDirectiveValue.Replace, request.MetadataDirective);

            request.MetadataDirective = null;

            Assert.Null(request.MetadataDirective);
        }
 /// <summary>
 /// Start the asynchronous request for copying an object.
 /// </summary>
 /// <param name="request">Parameters in a request for copying an object</param>
 /// <param name="callback">Asynchronous request callback function</param>
 /// <param name="state">Asynchronous request status object</param>
 /// <returns>Response to the asynchronous request</returns>
 public IAsyncResult BeginCopyObject(CopyObjectRequest request, AsyncCallback callback, object state)
 {
     return(this.BeginDoRequest <CopyObjectRequest>(request, delegate()
     {
         if (request.ObjectKey == null)
         {
             throw new ObsException(Constants.InvalidObjectKeyMessage, ErrorType.Sender, Constants.InvalidObjectKey, "");
         }
         if (string.IsNullOrEmpty(request.SourceBucketName))
         {
             throw new ObsException(Constants.InvalidSourceBucketNameMessage, ErrorType.Sender, Constants.InvalidBucketName, "");
         }
         if (request.SourceObjectKey == null)
         {
             throw new ObsException(Constants.InvalidSourceObjectKeyMessage, ErrorType.Sender, Constants.InvalidObjectKey, "");
         }
     }, callback, state));
 }
        /// <summary>
        /// Sets the properties, like cacheControl, content type, etc.
        /// </summary>
        /// <param name="location">Descriptor of the item on the remote blob storage.</param>
        /// <param name="properties">The properties to set.</param>
        public override void SetProperties(IBlobContentLocation location, IBlobProperties properties)
        {
            //No properties to set by default
            var req = new CopyObjectRequest()
            {
                MetadataDirective = S3MetadataDirective.REPLACE,
                SourceBucket      = this.bucketName,
                SourceKey         = location.FilePath,
                DestinationBucket = this.bucketName,
                DestinationKey    = location.FilePath,
                CannedACL         = S3CannedACL.PublicRead
            };

            req.Headers.CacheControl = properties.CacheControl;
            req.Headers.ContentType  = properties.ContentType;

            transferUtility.S3Client.CopyObject(req);
        }
예제 #27
0
 /// <summary>
 /// Copy an object.
 /// </summary>
 /// <param name="request">Parameters in a request for copying an object</param>
 /// <returns> Response to an object copy request</returns>
 public CopyObjectResponse CopyObject(CopyObjectRequest request)
 {
     return(this.DoRequest <CopyObjectRequest, CopyObjectResponse>(request, delegate()
     {
         if (request.ObjectKey == null)
         {
             throw new ObsException(Constants.InvalidObjectKeyMessage, ErrorType.Sender, Constants.InvalidObjectKey, "");
         }
         if (string.IsNullOrEmpty(request.SourceBucketName))
         {
             throw new ObsException(Constants.InvalidSourceBucketNameMessage, ErrorType.Sender, Constants.InvalidBucketName, "");
         }
         if (request.SourceObjectKey == null)
         {
             throw new ObsException(Constants.InvalidSourceObjectKeyMessage, ErrorType.Sender, Constants.InvalidObjectKey, "");
         }
     }));
 }
        /// <summary>
        /// moves file (object) between bucket folders
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sourceDirectory"></param>
        /// <param name="destDirectory"></param>
        /// <returns></returns>
        public async Task <bool> MoveFileAsync(string fileName, string sourceDirectory, string destDirectory)
        {
            try
            {
                var copyRequest = new CopyObjectRequest
                {
                    SourceBucket      = _s3BucketOptions.BucketName + @"/" + sourceDirectory,
                    SourceKey         = fileName,
                    DestinationBucket = _s3BucketOptions.BucketName + @"/" + destDirectory,
                    DestinationKey    = fileName
                };
                var response = await _s3Client.CopyObjectAsync(copyRequest);

                if (response.HttpStatusCode == HttpStatusCode.OK)
                {
                    var deleteRequest = new DeleteObjectRequest
                    {
                        BucketName = _s3BucketOptions.BucketName + @"/" + sourceDirectory,
                        Key        = fileName
                    };
                    await _s3Client.DeleteObjectAsync(deleteRequest);

                    return(true);
                }

                return(false);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                }
                else
                {
                    _logger.LogError("An error occurred with the message '{0}' when moving object",
                                     amazonS3Exception.Message);
                }

                return(false);
            }
        }
예제 #29
0
        public void CopyObjectMatchingETagNegativeTest()
        {
            var targetObjectKey = OssTestUtils.GetObjectKey(_className);

            var coRequest = new CopyObjectRequest(_bucketName, _sourceObjectKey, _bucketName, targetObjectKey);

            coRequest.MatchingETagConstraints.Add("Dummy");

            try
            {
                _ossClient.CopyObject(coRequest);
                Assert.Fail("Copy object should not pass with MatchingETag set to wrong value");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.PreconditionFailed, e.ErrorCode);
            }
            Assert.IsFalse(OssTestUtils.ObjectExists(_ossClient, _bucketName, targetObjectKey));
        }
예제 #30
0
        /// <summary>
        /// 拷贝小文件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="sourceBucket">源空间</param>
        /// <param name="sourceKey">源文件</param>
        /// <param name="optBucket">目标空间</param>
        /// <param name="optKey">目标文件</param>
        /// <returns></returns>
        private CopyFileResultDto CopySmallFile(OssClient client, string sourceBucket, string sourceKey,
                                                string optBucket, string optKey)
        {
            var req = new CopyObjectRequest(sourceBucket, sourceKey, optBucket, optKey)
            {
                NewObjectMetadata =
                    null // 如果NewObjectMetadata为null则为COPY模式(即拷贝源文件的元信息),非null则为REPLACE模式(覆盖源文件的元信息)。
            };
            // 拷贝文件。
            var ret = client.CopyObject(req);

            if (ret.HttpStatusCode == HttpStatusCode.OK)
            {
                return(new CopyFileResultDto(true, sourceKey, "success"));
            }

            return(new CopyFileResultDto(false, sourceKey,
                                         $"RequestId:{ret.RequestId},HttpStatusCode:{ret.HttpStatusCode}"));
        }
예제 #31
0
        public void CopyObjectValidAccessPoint()
        {
            var accessPointDestinationArn = "arn:aws:s3:us-east-1:000011112222:accesspoint/destinationpoint";
            var accessPointSourceArn      = "arn:aws:s3:us-east-1:000011112222:accesspoint/sourcepoint";

            var request = new CopyObjectRequest
            {
                SourceBucket      = accessPointSourceArn,
                SourceKey         = "source.txt",
                DestinationBucket = accessPointDestinationArn,
                DestinationKey    = "dest.txt"
            };

            var internalRequest = S3ArnTestUtils.RunMockRequest(request, CopyObjectRequestMarshaller.Instance);

            Assert.AreEqual(new Uri("https://destinationpoint-000011112222.s3-accesspoint.us-east-1.amazonaws.com"), internalRequest.Endpoint);
            Assert.AreEqual("/dest.txt", internalRequest.ResourcePath);
            Assert.AreEqual("arn%3Aaws%3As3%3Aus-east-1%3A000011112222%3Aaccesspoint%2Fsourcepoint%2Fobject%2Fsource.txt", internalRequest.Headers["x-amz-copy-source"]);
        }
예제 #32
0
 public static void ResumableCopyObject(string sourceBucketName, string sourceKey, 
                                        string destBucketName, string destKey)
 {
     
     string checkpointDir = Config.DirToDownload;
     try
     {
         var request = new CopyObjectRequest(sourceBucketName, sourceKey, destBucketName, destKey);
         client.ResumableCopyObject(request, checkpointDir);
         Console.WriteLine("Resumable copy new object:{0} succeeded", request.DestinationKey);
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
             ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
예제 #33
0
 public static void CopyObject()
 {
     try
     {
         var metadata = new ObjectMetadata();
         metadata.AddHeader("mk1", "mv1");
         metadata.AddHeader("mk2", "mv2");
         var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
         {
             NewObjectMetadata = metadata
         };
         var ret = client.CopyObject(req);
         Console.WriteLine("target key's etag: " + ret.ETag);
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
             ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
예제 #34
0
파일: S3Service.cs 프로젝트: ngs-doo/revenj
        /// <summary>
        /// Copies an object from one bucket to another.
        /// </summary>
        public void CopyObject(string sourceBucketName, string sourceKey,
            string destBucketName, string destKey)
        {
            var request = new CopyObjectRequest(this, sourceBucketName, sourceKey,
                destBucketName, destKey);

            CopyObjectResponse response = request.GetResponse();
            response.Close();

            if (response.Error != null)
                throw response.Error;
        }