BosClientSample.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. <?php
  2. /*
  3. * Copyright 2014 Baidu, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  6. * use this file except in compliance with the License. You may obtain a copy of
  7. * the License at
  8. *
  9. * Http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. include 'BaiduBce.phar';
  18. require 'YourConf.php';
  19. use BaiduBce\BceClientConfigOptions;
  20. use BaiduBce\Util\Time;
  21. use BaiduBce\Util\MimeTypes;
  22. use BaiduBce\Http\HttpHeaders;
  23. use BaiduBce\Services\Bos\BosClient;
  24. use BaiduBce\Services\Bos\CannedAcl;
  25. use BaiduBce\Services\Bos\BosOptions;
  26. use BaiduBce\Auth\SignOptions;
  27. use BaiduBce\Services\Bos\StorageClass;
  28. use BaiduBce\Log\LogFactory;
  29. use PHPUnit\Framework\TestCase;
  30. class BosClientTest extends TestCase
  31. {
  32. private $client;
  33. private $bucket;
  34. private $custom_client;
  35. private $custom_bucket;
  36. private $key;
  37. private $filename;
  38. private $download;
  39. public function __construct()
  40. {
  41. global $BOS_TEST_CONFIG;
  42. global $CUSTOM_BOS_TEST_CONFIG;
  43. parent::__construct();
  44. $this->client = new BosClient($BOS_TEST_CONFIG);
  45. // $this->custom_client = new BosClient($CUSTOM_BOS_TEST_CONFIG);
  46. $this->logger = LogFactory::getLogger(get_class($this));
  47. }
  48. public function setUp():void
  49. {
  50. $id = rand();
  51. $this->bucket = sprintf('test-bucket%d', $id);
  52. $this->key = sprintf('test_object%d', $id);
  53. $this->filename = sprintf(__DIR__.'\\'.'temp_file%d.txt', $id);
  54. $this->download = __DIR__.'\\'.'download.txt';
  55. $this->client->createBucket($this->bucket);
  56. }
  57. public function tearDown():void
  58. {
  59. // Delete all buckets
  60. $response = $this->client->listBuckets();
  61. foreach ($response->buckets as $bucket) {
  62. if (substr($bucket->name, 0, 11) == 'test-bucket') {
  63. $response = $this->client->listObjects($bucket->name);
  64. foreach ($response->contents as $object) {
  65. $this->client->deleteObject($bucket->name, $object->key);
  66. }
  67. $this->client->deleteBucket($bucket->name);
  68. }
  69. }
  70. if (file_exists($this->filename)) {
  71. unlink($this->filename);
  72. }
  73. if (file_exists($this->download)) {
  74. unlink($this->download);
  75. }
  76. }
  77. /**
  78. * Generate a random file of specified size
  79. * @param int $size The size of generated file.
  80. * @return null
  81. */
  82. private function prepareTemporaryFile($size)
  83. {
  84. $fp = fopen($this->filename, 'w');
  85. fseek($fp, $size - 1, SEEK_SET);
  86. fwrite($fp, '0');
  87. fclose($fp);
  88. }
  89. //test of bucket create/doesExist/list/delete operations
  90. public function testBucketOperations()
  91. {
  92. $id = rand();
  93. $bucketName = "test-bucket-operations".$id;
  94. //not created, should be false
  95. $exist = $this->client->doesBucketExist($bucketName);
  96. $this->assertFalse($exist);
  97. //create bucket
  98. $this->client->createBucket($bucketName);
  99. //created, should be true
  100. $exist = $this->client->doesBucketExist($bucketName);
  101. $this->assertTrue($exist);
  102. //should be in the bucket list
  103. $exist = false;
  104. $response = $this->client->listBuckets();
  105. foreach ($response->buckets as $bucket) {
  106. if ($bucket->name == $bucketName) {
  107. $exist = true;
  108. }
  109. }
  110. $this->assertTrue($exist);
  111. //delete
  112. $this->client->deleteBucket($bucketName);
  113. //deleted should be false
  114. $exist = $this->client->doesBucketExist($bucketName);
  115. $this->assertFalse($exist);
  116. }
  117. //test of acl set/set canned/get
  118. public function testAclOperations()
  119. {
  120. //there is no public-read-write
  121. $result = $this->client->getBucketAcl($this->bucket);
  122. $found = false;
  123. foreach($result->accessControlList as $acl) {
  124. if(strcmp($acl->grantee[0]->id, '*') == 0) {
  125. $this->assertEquals($acl->permission[0], 'READ');
  126. $this->assertEquals($acl->permission[1], 'WRITE');
  127. $found = true;
  128. }
  129. }
  130. $this->assertFalse($found);
  131. //there is public-read-write
  132. $this->client->setBucketCannedAcl($this->bucket, CannedAcl::ACL_PUBLIC_READ_WRITE);
  133. $result = $this->client->getBucketAcl($this->bucket);
  134. $found = false;
  135. foreach($result->accessControlList as $acl) {
  136. if(strcmp($acl->grantee[0]->id, '*') == 0) {
  137. $this->assertEquals($acl->permission[0], 'READ');
  138. $this->assertEquals($acl->permission[1], 'WRITE');
  139. $found = true;
  140. }
  141. }
  142. $this->assertTrue($found);
  143. //upload customized acl
  144. $found = false;
  145. $myAcl = array(
  146. array(
  147. 'grantee' => array(
  148. array(
  149. 'id' => 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
  150. ),
  151. array(
  152. 'id' => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  153. ),
  154. ),
  155. 'permission' => array('FULL_CONTROL'),
  156. ),
  157. );
  158. $this->client->setBucketAcl($this->bucket, $myAcl);
  159. $result = $this->client->getBucketAcl($this->bucket);
  160. foreach($result->accessControlList as $acl) {
  161. foreach($acl->grantee as $grantee) {
  162. if(strcmp($grantee->id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') == 0) {
  163. $found = true;
  164. $this->assertEquals($acl->permission[0], 'FULL_CONTROL');
  165. }
  166. }
  167. }
  168. $this->assertTrue($found);
  169. }
  170. //test of object acl set/set canned/get
  171. public function testObjectAclOperations()
  172. {
  173. //put string
  174. $this->client->putObjectFromString($this->bucket, $this->key, 'test');
  175. // set object acl private
  176. $canned_acl = array("x-bce-acl" => "private");
  177. $this->client->setObjectCannedAcl($this->bucket, $this->key, $canned_acl);
  178. //there is no public-read-write
  179. $result = $this->client->getObjectAcl($this->bucket, $this->key);
  180. $found = false;
  181. foreach ($result->accessControlList as $acl) {
  182. if (strcmp($acl->grantee[0]->id, '*') == 0) {
  183. $this->assertEquals($acl->permission[0], 'READ');
  184. $this->assertEquals($acl->permission[1], 'WRITE');
  185. $found = true;
  186. }
  187. }
  188. $this->assertFalse($found);
  189. //there is public-read
  190. $canned_acl = array("x-bce-acl" => "public-read");
  191. $this->client->setObjectCannedAcl($this->bucket, $this->key, $canned_acl);
  192. $result = $this->client->getObjectAcl($this->bucket, $this->key);
  193. $found = false;
  194. foreach ($result->accessControlList as $acl) {
  195. if (strcmp($acl->grantee[0]->id, '*') == 0) {
  196. $this->assertEquals($acl->permission[0], 'READ');
  197. $found = true;
  198. }
  199. }
  200. $this->assertTrue($found);
  201. //set object acl x-bce-grant-read
  202. $canned_acl = array("x-bce-grant-read" => "id=\"6c47a952\",id=\"8c47a95\"");
  203. $this->client->setObjectCannedAcl($this->bucket, $this->key, $canned_acl);
  204. $result = $this->client->getObjectAcl($this->bucket, $this->key);
  205. $found = 0;
  206. $acl = $result->accessControlList[0];
  207. if (strcmp($acl->grantee[0]->id, '6c47a952') == 0) {
  208. $this->assertEquals($acl->permission[0], 'READ');
  209. $found++;
  210. }
  211. if (strcmp($acl->grantee[1]->id, '8c47a95') == 0) {
  212. $this->assertEquals($acl->permission[0], 'READ');
  213. $found++;
  214. }
  215. $this->assertEquals($found, 2);
  216. //set object acl x-bce-grant-full-control
  217. $canned_acl = array("x-bce-grant-full-control" => "id=\"6c47a953\",id=\"8c47a96\"");
  218. $this->client->setObjectCannedAcl($this->bucket, $this->key, $canned_acl);
  219. $result = $this->client->getObjectAcl($this->bucket, $this->key);
  220. $found = 0;
  221. $acl = $result->accessControlList[0];
  222. if (strcmp($acl->grantee[0]->id, '6c47a953') == 0) {
  223. $this->assertEquals($acl->permission[0], 'FULL_CONTROL');
  224. $found++;
  225. }
  226. if (strcmp($acl->grantee[1]->id, '8c47a96') == 0) {
  227. $this->assertEquals($acl->permission[0], 'FULL_CONTROL');
  228. $found++;
  229. }
  230. $this->assertEquals($found, 2);
  231. //upload customized acl
  232. $found = false;
  233. $my_acl = array(
  234. array(
  235. 'grantee' => array(
  236. array(
  237. 'id' => '7f34788d02a64a9c98f85600567d98a7',
  238. ),
  239. array(
  240. 'id' => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  241. ),
  242. ),
  243. 'permission' => array('FULL_CONTROL'),
  244. ),
  245. );
  246. $this->client->setObjectAcl($this->bucket, $this->key, $my_acl);
  247. $result = $this->client->getObjectAcl($this->bucket, $this->key);
  248. foreach ($result->accessControlList as $acl) {
  249. foreach ($acl->grantee as $grantee) {
  250. if (strcmp($grantee->id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') ==
  251. 0
  252. ) {
  253. $found = true;
  254. $this->assertEquals($acl->permission[0], 'FULL_CONTROL');
  255. }
  256. }
  257. }
  258. $this->assertTrue($found);
  259. }
  260. //test of object operations basic:
  261. //List; listObjects
  262. //Delete: deleteObject
  263. //Copy: copyObject
  264. //Put: putObjectFromString/putObjectFromFile
  265. //Get: getObjectAsString/getObjectToFile
  266. public function testObjectBasicOperations()
  267. {
  268. $this->objectBasicOperations($this->client, $this->bucket);
  269. }
  270. /**
  271. * Operate object in bucket.
  272. * @param BosClient $client The bos client.
  273. * @param string $bucket The bucket name.
  274. * @return null
  275. */
  276. public function objectBasicOperations($client, $bucket)
  277. {
  278. //put string
  279. $client->putObjectFromString($bucket, $this->key, 'test');
  280. //put file
  281. file_put_contents($this->filename, "test of put object from string");
  282. $otherKey = $this->key."other";
  283. $client->putObjectFromFile($bucket, $otherKey, $this->filename);
  284. //list the objects and check
  285. $response = $client->listObjects($bucket);
  286. $keyArr = array(
  287. $this->key => false,
  288. $otherKey => false,
  289. );
  290. $this->assertEquals(2, count($response->contents));
  291. foreach ($response->contents as $object) {
  292. foreach(array_keys($keyArr) as $tempKey) {
  293. if(strcasecmp($object->key, $tempKey) == 0) {
  294. unset($keyArr[$tempKey]);
  295. break;
  296. }
  297. }
  298. }
  299. $this->assertEquals(0, count($keyArr));
  300. //copy object
  301. $response = $client->copyObject($bucket, $this->key, $bucket, "copy_of_test");
  302. //list the bucket and check
  303. $response = $client->listObjects($bucket);
  304. $keyArr = array(
  305. $this->key => false,
  306. $otherKey => false,
  307. "copy_of_test" => false,
  308. );
  309. $this->assertEquals(3, count($response->contents));
  310. foreach ($response->contents as $object) {
  311. foreach(array_keys($keyArr) as $tempKey) {
  312. if(strcasecmp($object->key, $tempKey) == 0) {
  313. unset($keyArr[$tempKey]);
  314. break;
  315. }
  316. }
  317. }
  318. $this->assertEquals(0, count($keyArr));
  319. //delete object
  320. $client->deleteObject($bucket, "copy_of_test");
  321. //list the bucket and check
  322. $response = $client->listObjects($bucket);
  323. $keyArr = array(
  324. $this->key => false,
  325. $otherKey => false,
  326. "copy_of_test" => false,
  327. );
  328. $this->assertEquals(2, count($response->contents));
  329. foreach ($response->contents as $object) {
  330. foreach(array_keys($keyArr) as $tempKey) {
  331. if(strcasecmp($object->key, $tempKey) == 0) {
  332. unset($keyArr[$tempKey]);
  333. break;
  334. }
  335. }
  336. }
  337. $this->assertEquals(1, count($keyArr));
  338. $this->assertTrue(array_key_exists("copy_of_test", $keyArr));
  339. //get object as string
  340. $result = $client->getObjectAsString($bucket, $otherKey);
  341. $this->assertStringEqualsFile($this->filename, $result);
  342. //get object to file
  343. $client->getObjectToFile($bucket, $this->key, $this->download);
  344. $this->assertStringEqualsFile($this->download, 'test');
  345. // append object
  346. file_put_contents($this->filename, "test of put append object");
  347. $appendKey = $this->key."append";
  348. $response = $client->appendObjectFromFile($bucket, $appendKey, $this->filename, 0);
  349. $nextOffsetTmp = $response->metadata[BosOptions::NEXT_APPEND_OFFSET];
  350. $appendStr = "appendStr";
  351. $response = $client->appendObjectFromString($bucket, $appendKey, $appendStr, intval($nextOffsetTmp));
  352. $nextOffset = $response->metadata[BosOptions::NEXT_APPEND_OFFSET];
  353. $this->assertEquals($nextOffset, strlen($appendStr) + $nextOffsetTmp);
  354. }
  355. //test of object operations advanced:
  356. //List; listObjects
  357. //Delete: deleteObject
  358. //Copy: copyObject
  359. //Put: putObjectFromString/putObjectFromFile
  360. //Get: getObjectAsString/getObjectToFile
  361. public function testObjectAdvancedOperations()
  362. {
  363. //put object from file with options
  364. file_put_contents($this->filename, "test of put object from string");
  365. $userMeta = array("private" => "private data");
  366. $options = array(
  367. BosOptions::CONTENT_TYPE=>"text/plain",
  368. BosOptions::CONTENT_MD5=>base64_encode(hash_file("md5", $this->filename, true)),
  369. BosOptions::CONTENT_LENGTH=>filesize($this->filename),
  370. BosOptions::CONTENT_SHA256=>hash_file("sha256", $this->filename),
  371. BosOptions::USER_METADATA => $userMeta,
  372. );
  373. $response = $this->client->putObjectFromFile($this->bucket, $this->key, $this->filename, $options);
  374. //stash etag which will be used in copy with options
  375. $sourceEtag = $response->metadata[BosOptions::ETAG];
  376. //get object with options:
  377. //get content from 12 to 17 in $this->key
  378. $options = array(
  379. BosOptions::RANGE=>array(12,17),
  380. );
  381. $slice = $this->client->getObjectAsString($this->bucket, $this->key, $options);
  382. $this->assertEquals("object", $slice);
  383. //put a dir and objects under this dir
  384. $this->client->putObjectFromString($this->bucket, "usr", '');
  385. for ($i = 0; $i < 10; $i++) {
  386. $this->client->putObjectFromString($this->bucket, "usr/".'object'.$i, "test".$i);
  387. }
  388. //list objects with options:
  389. //list 5 objects under dir usr start from usr/object4
  390. $options = array(
  391. BosOptions::MAX_KEYS=>5,
  392. BosOptions::PREFIX=>"usr/",
  393. BosOptions::MARKER=>"usr/object4",
  394. BosOptions::DELIMITER=>"/",
  395. );
  396. $response = $this->client->listObjects($this->bucket, $options);
  397. $this->assertEquals(5, count($response->contents));
  398. //copy object with options
  399. $options = array(
  400. BosOptions::USER_METADATA=>$userMeta,
  401. BosOptions::ETAG=>$sourceEtag,
  402. );
  403. $this->client->copyObject($this->bucket, $this->key, $this->bucket, "copy_of_test", $options);
  404. //get user meta from source
  405. $response = $this->client->getObjectMetadata($this->bucket, $this->key);
  406. $this->assertTrue(array_key_exists('private', $response['userMetadata']));
  407. $this->assertEquals('private data', $response['userMetadata']['private']);
  408. //get user meta from copy
  409. $response = $this->client->getObjectMetadata($this->bucket, "copy_of_test");
  410. $this->assertTrue(array_key_exists('private', $response['userMetadata']));
  411. $this->assertEquals('private data', $response['userMetadata']['private']);
  412. }
  413. //test of multi-part operations
  414. public function testMultiPartBaseOperations() {
  415. //initiate multi-upload
  416. $response = $this->client->initiateMultipartUpload($this->bucket, $this->key);
  417. $uploadId1 =$response->uploadId;
  418. $response = $this->client->initiateMultipartUpload($this->bucket, $this->key);
  419. $uploadId2 =$response->uploadId;
  420. //list multi-upload and check
  421. $upload_array = array(
  422. $uploadId1 => 0,
  423. $uploadId2 => 0,
  424. );
  425. $response = $this->client->listMultipartUploads($this->bucket);
  426. $this->assertEquals(2, count($response->uploads));
  427. foreach($response->uploads as $upload) {
  428. $this->assertEquals($upload->key, $this->key);
  429. $this->assertTrue(array_key_exists($upload->uploadId, $upload_array));
  430. }
  431. //about multi-upload
  432. $this->client->abortMultipartUpload($this->bucket, $this->key, $uploadId2);
  433. //list multi-upload and check
  434. $response = $this->client->listMultipartUploads($this->bucket);
  435. $this->assertEquals(1, count($response->uploads));
  436. $this->assertEquals($uploadId1, $response->uploads[0]->uploadId);
  437. $this->assertNotEquals($uploadId2, $response->uploads[0]->uploadId);
  438. //upload part from file
  439. $this->prepareTemporaryFile(6 * 1024 * 1024);
  440. $eTags = array();
  441. $partList = array();
  442. $response = $this->client->uploadPartFromFile($this->bucket,
  443. $this->key,
  444. $uploadId1,
  445. 1,
  446. $this->filename,
  447. 0,
  448. 5*1024*1024);
  449. $eTags[$response->metadata[BosOptions::ETAG]] = true;
  450. array_push($partList, array("partNumber"=>1, "eTag"=>$response->metadata[BosOptions::ETAG]));
  451. $response = $this->client->uploadPartFromFile($this->bucket,
  452. $this->key,
  453. $uploadId1,
  454. 2,
  455. $this->filename,
  456. 5*1024*1024,
  457. 1*1024*1024);
  458. $eTags[$response->metadata[BosOptions::ETAG]] = true;
  459. array_push($partList, array("partNumber"=>2, "eTag"=>$response->metadata[BosOptions::ETAG]));
  460. //list parts and compare
  461. $response = $this->client->listParts($this->bucket, $this->key, $uploadId1);
  462. $this->assertEquals(2, count($response->parts));
  463. foreach($response->parts as $part) {
  464. $this->assertTrue(array_key_exists($part->eTag, $eTags));
  465. }
  466. //complete multi-upload
  467. $response = $this->client->completeMultipartUpload($this->bucket, $this->key, $uploadId1, $partList);
  468. //download it and compare
  469. $this->client->getObjectToFile($this->bucket, $this->key, $this->download);
  470. $this->assertFileEquals($this->filename, $this->download);
  471. }
  472. public function testMultiPartCopyOperations() {
  473. //prepare file
  474. $fileSize = 21 * 1024 * 1024;
  475. $partSize = 5 * 1024 * 1024;
  476. $this->prepareTemporaryFile($fileSize);
  477. $this->client->putObjectFromFile($this->bucket, $this->key, $this->filename);
  478. //multi-upload
  479. $partNumber = 1;
  480. $length = $partSize;
  481. $bytesLeft = $fileSize;
  482. $offSet = 0;
  483. $partList = array();
  484. $response = $this->client->initiateMultipartUpload($this->bucket, $this->key."_multi_copy");
  485. $uploadId =$response->uploadId;
  486. while ($bytesLeft > 0) {
  487. $length = ($length > $bytesLeft) ? $bytesLeft : $length;
  488. $options = array(
  489. BosOptions::RANGE => array($offSet, $offSet + $length - 1)
  490. );
  491. $response = $this->client->uploadPartCopy($this->bucket,
  492. $this->key,
  493. $this->bucket,
  494. $this->key."_multi_copy",
  495. $uploadId,
  496. $partNumber,
  497. $options
  498. );
  499. array_push(
  500. $partList,
  501. array("partNumber"=>$partNumber, "eTag"=>$response->eTag)
  502. );
  503. $partNumber++;
  504. $bytesLeft -= $length;
  505. $offSet += $length;
  506. }
  507. //list parts with options
  508. $options = array(
  509. BosOptions::LIMIT=>5,
  510. );
  511. $response = $this->client->listParts($this->bucket, $this->key."_multi_copy", $uploadId, $options);
  512. $this->assertEquals(5, count($response->parts));
  513. //complete multi part upload
  514. $this->client->completeMultipartUpload($this->bucket, $this->key."_multi_copy", $uploadId, $partList);
  515. //compare content length with file size
  516. $contentLength = $this->client->getObjectMetadata($this->bucket, $this->key."_multi_copy")["contentLength"];
  517. $this->assertEquals($contentLength, $fileSize);
  518. $this->client->deleteObject($this->bucket, $this->key."_multi_copy");
  519. }
  520. //test of multi-part operations
  521. public function testMultiPartAdvancedOperations() {
  522. //prepare file
  523. $fileSize = 101 * 1024 * 1024;
  524. $partSize = 5 * 1024 * 1024;
  525. $this->prepareTemporaryFile($fileSize);
  526. //multi-upload
  527. $userMeta = array("private" => "private data");
  528. $offset = 0;
  529. $partNumber = 1;
  530. $length = $partSize;
  531. $bytesLeft = $fileSize;
  532. $partList = array();
  533. $response = $this->client->initiateMultipartUpload($this->bucket, $this->key);
  534. $uploadId =$response->uploadId;
  535. while ($bytesLeft > 0) {
  536. $length = ($length > $bytesLeft) ? $bytesLeft : $length;
  537. $response = $this->client->uploadPartFromFile($this->bucket,
  538. $this->key,
  539. $uploadId,
  540. $partNumber,
  541. $this->filename,
  542. $offset,
  543. $length);
  544. array_push(
  545. $partList,
  546. array("partNumber"=>$partNumber, "eTag"=>$response->metadata[BosOptions::ETAG],)
  547. );
  548. $offset += $length;
  549. $partNumber++;
  550. $bytesLeft -= $length;
  551. }
  552. //list parts with options
  553. $options = array(
  554. BosOptions::LIMIT=>5,
  555. BosOptions::MARKER=>5,
  556. );
  557. $response = $this->client->listParts($this->bucket, $this->key, $uploadId, $options);
  558. $this->assertEquals(5, count($response->parts));
  559. //complete with user-metadata
  560. $options = array(BosOptions::USER_METADATA => $userMeta,);
  561. $this->client->completeMultipartUpload($this->bucket, $this->key, $uploadId, $partList, $options);
  562. //get user meta
  563. $response = $this->client->getObjectMetadata($this->bucket, $this->key);
  564. $this->assertTrue(array_key_exists('private', $response['userMetadata']));
  565. $this->assertEquals('private data', $response['userMetadata']['private']);
  566. //put a dir and init multi-upload for each object under dir
  567. $uploadIdList = array();
  568. $this->client->putObjectFromString($this->bucket, "usr", '');
  569. for ($i = 0; $i < 10; $i++) {
  570. $response = $this->client->initiateMultipartUpload($this->bucket, "usr/".'object'.$i);
  571. $uploadIdList["usr/".'object'.$i] = $response->uploadId;
  572. }
  573. //list objects with options:
  574. //list 5 objects under dir usr start from usr/object4
  575. $options = array(
  576. BosOptions::LIMIT=>5,
  577. BosOptions::PREFIX=>"usr/",
  578. BosOptions::MARKER=>"usr/object4",
  579. BosOptions::DELIMITER=>"/",
  580. );
  581. $response = $this->client->listMultipartUploads($this->bucket, $options);
  582. $this->assertEquals(5, count($response->uploads));
  583. //clear env
  584. foreach ($uploadIdList as $key => $uploadId) {
  585. $this->client->abortMultipartUpload($this->bucket, $key, $uploadId);
  586. }
  587. }
  588. public function testPutSuperObjectFromFile() {
  589. //prepare file
  590. $fileSize = 101 * 1024 * 1024;
  591. $partSize = 5 * 1024 * 1024;
  592. $this->prepareTemporaryFile($fileSize);
  593. $userMeta = array("private" => "private data");
  594. $options = array(BosOptions::USER_METADATA => $userMeta);
  595. $this->client->putSuperObjectFromFile($this->bucket, $this->key, $this->filename, $options);
  596. //get user meta
  597. $response = $this->client->getObjectMetadata($this->bucket, $this->key);
  598. $this->assertTrue(array_key_exists('private', $response['userMetadata']));
  599. $this->assertEquals('private data', $response['userMetadata']['private']);
  600. }
  601. //test of misc functions:generatePreSignedUrl
  602. public function testMiscOperations() {
  603. //put an object
  604. $this->client->putObjectFromString($this->bucket, $this->key, 'test string');
  605. //generatePreSignedUrl
  606. $url = $this->client->generatePreSignedUrl($this->bucket, $this->key);
  607. $file = file_get_contents($url);
  608. $this->assertEquals('test string', $file);
  609. //generatePreSignedUrl with timestamp and expiration
  610. $signOptions = array(
  611. SignOptions::TIMESTAMP=>new \DateTime(),
  612. SignOptions::EXPIRATION_IN_SECONDS=>300,
  613. );
  614. $url = $this->client->generatePreSignedUrl($this->bucket,
  615. $this->key,
  616. array(BosOptions::SIGN_OPTIONS => $signOptions)
  617. );
  618. $file = file_get_contents($url);
  619. $this->assertEquals('test string', $file);
  620. }
  621. // test of client config with custom endpoint
  622. public function testCustomObjectBasicOperations()
  623. {
  624. // If want to test custom endpoint, comment markTestSkipped and modify endpoint of $CUSTOM_BOS_TEST_CONFIG to custom endpoint
  625. $this->markTestSkipped(
  626. 'Skip custom endpoint Case'
  627. );
  628. // modify it to your bucket associated with custom endpoint
  629. // for example, 'endpoint' => 'http://cus-bucket.bj.bcebos.com', custom_bucket = "cus-bucket"
  630. $this->custom_bucket = "your bucket name";
  631. $this->objectBasicOperations($this->custom_client, $this->custom_bucket);
  632. $custom_response = $this->custom_client->listObjects($this->custom_bucket);
  633. foreach ($custom_response->contents as $object) {
  634. $this->custom_client->deleteObject($this->custom_bucket, $object->key);
  635. }
  636. }
  637. // test of put/get/delete bucket replication and get bucket replication progress
  638. public function testBucketReplicationOperation()
  639. {
  640. $this->markTestSkipped(
  641. 'Skip Replication Case'
  642. );
  643. $replication_rule = array(
  644. 'status' => 'enabled',
  645. 'replicateDeletes' => 'enabled',
  646. 'id' => 'sample'
  647. );
  648. $replication_rule['resource'][0] = $this->bj_bucket . "/*";
  649. $replication_rule['destination']['bucket'] = $this->gz_bucket;
  650. $replication_rule['replicateHistory']['bucket'] = $this->gz_bucket;
  651. $this->bj_client->putBucketReplication($this->bj_bucket, $replication_rule);
  652. sleep(2);
  653. $this->bj_client->putObjectFromString($this->bj_bucket, "increment", "content");
  654. sleep(60);
  655. $response = $this->bj_client->getBucketReplicationProgress($this->bj_bucket);
  656. $this->assertEquals($response->historyReplicationPercent, 100);
  657. $response = $this->bj_client->getBucketReplication($this->bj_bucket);
  658. $this->assertEquals($response->status, "enabled");
  659. $response = $this->bj_client->listBucketReplication($this->bj_bucket);
  660. $response = $this->bj_client->deleteBucketReplication($this->bj_bucket);
  661. }
  662. //test of bucket put/get/delete lifecycle operations
  663. public function testBucketLifecycleOperations() {
  664. $lifecycle_rule = array(
  665. array(
  666. 'id' => 'rule-id0',
  667. 'status' => 'enabled',
  668. 'resource' => array(
  669. $this->bucket.'/prefix/*',
  670. ),
  671. 'condition' => array(
  672. 'time' => array(
  673. 'dateGreaterThan' => '2016-09-07T00:00:00Z',
  674. ),
  675. ),
  676. 'action' => array(
  677. 'name' => 'DeleteObject',
  678. )
  679. ),
  680. array(
  681. 'id' => 'rule-id1',
  682. 'status' => 'disabled',
  683. 'resource' => array(
  684. $this->bucket.'/prefix/*',
  685. ),
  686. 'condition' => array(
  687. 'time' => array(
  688. 'dateGreaterThan' => '2016-09-07T00:00:00Z',
  689. ),
  690. ),
  691. 'action' => array(
  692. 'name' => 'Transition',
  693. 'storageClass' => 'COLD',
  694. ),
  695. ),
  696. );
  697. $this->client->putBucketLifecycle($this->bucket, $lifecycle_rule);
  698. $lifecycle_ret = $this->client->getBucketLifecycle($this->bucket);
  699. $this->assertEquals(sizeof($lifecycle_ret->rule), 2);
  700. $this->assertEquals($lifecycle_ret->rule[0]->status, 'enabled');
  701. $this->assertEquals($lifecycle_ret->rule[1]->action->name, 'Transition');
  702. $this->client->deleteBucketLifecycle($this->bucket);
  703. }
  704. //test of bucket put/get/delete logging operations
  705. public function testBucketLoggingOperations() {
  706. // prepare target bucket
  707. $this->client->createBucket($this->bucket.'logging');
  708. $logging = array(
  709. 'targetBucket' => $this->bucket.'logging',
  710. 'targetPrefix' => 'TargetPrefixName'
  711. );
  712. $this->client->putBucketLogging($this->bucket, $logging);
  713. $logging_ret = $this->client->getBucketLogging($this->bucket);
  714. $this->assertEquals($logging_ret->status, 'enabled');
  715. $this->assertEquals($logging_ret->targetPrefix, 'TargetPrefixName');
  716. $this->client->deleteBucketLogging($this->bucket);
  717. $this->client->deleteBucket($this->bucket.'logging');
  718. }
  719. //test of bucket put/get/delete trash operations
  720. public function testBucketTrashOperations() {
  721. $this->client->putBucketTrash($this->bucket, '.trashDirName');
  722. $trash_ret = $this->client->getBucketTrash($this->bucket);
  723. $this->assertEquals($trash_ret->trashDir, '.trashDirName');
  724. $this->client->deleteBucketTrash($this->bucket);
  725. }
  726. //test of bucket put/get/delete static website operations
  727. public function testBucketStaticWebsiteOperations() {
  728. $static_website = array(
  729. 'index' => 'index.html',
  730. 'notFound' => '404.html'
  731. );
  732. $this->client->putBucketStaticWebsite($this->bucket, $static_website);
  733. $static_website_ret = $this->client->getBucketStaticWebsite($this->bucket);
  734. $this->assertEquals($static_website_ret->index, 'index.html');
  735. $this->assertEquals($static_website_ret->notFound, '404.html');
  736. $this->client->deleteBucketStaticWebsite($this->bucket);
  737. }
  738. //test of bucket put/get/delete encryption operations
  739. public function testBucketEncryptionOperations() {
  740. $this->client->putBucketEncryption($this->bucket, 'AES256');
  741. $encryption_ret = $this->client->getBucketEncryption($this->bucket);
  742. $this->assertEquals($encryption_ret->encryptionAlgorithm, 'AES256');
  743. $this->client->deleteBucketEncryption($this->bucket);
  744. }
  745. //test of bucket put/get/delete cors operations
  746. public function testBucketCorsOperations() {
  747. $cors_rule = array(
  748. array(
  749. 'allowedOrigins' => array(
  750. 'http://www.example.com',
  751. 'www.example2.com'
  752. ),
  753. 'allowedMethods' => array(
  754. 'GET',
  755. 'HEAD'
  756. ),
  757. 'allowedHeaders' => array(
  758. 'Authorization'
  759. ),
  760. 'allowedExposeHeaders' => array(
  761. 'user-custom-expose-header'
  762. ),
  763. 'maxAgeSeconds' => 3600
  764. ),
  765. array(
  766. 'allowedOrigins' => array(
  767. 'http://www.example3.com'
  768. ),
  769. 'allowedMethods' => array(
  770. 'GET',
  771. 'PUT'
  772. ),
  773. 'allowedHeaders' => array(
  774. 'x-bce-test'
  775. ),
  776. 'allowedExposeHeaders' => array(
  777. 'user-custom-expose-header'
  778. ),
  779. 'maxAgeSeconds' => 3600
  780. )
  781. );
  782. $this->client->putBucketCors($this->bucket, $cors_rule);
  783. $cors_ret = $this->client->getBucketCors($this->bucket);
  784. $this->assertEquals(sizeof($cors_ret->corsConfiguration), 2);
  785. $this->assertEquals($cors_ret->corsConfiguration[0]->maxAgeSeconds, 3600);
  786. $this->assertEquals($cors_ret->corsConfiguration[1]->allowedOrigins[0], 'http://www.example3.com');
  787. $this->client->deleteBucketCors($this->bucket);
  788. }
  789. //test of bucket put/get/delete copyright protection operations
  790. public function testBucketCopyrightProtectionOperations() {
  791. $copyright_protection = array(
  792. $this->bucket.'/prefix/*',
  793. $this->bucket.'/*/suffix'
  794. );
  795. $this->client->putBucketCopyrightProtection($this->bucket, $copyright_protection);
  796. $copyright_protection_ret = $this->client->getBucketCopyrightProtection($this->bucket);
  797. $this->assertEquals($copyright_protection_ret->resource[0], $this->bucket.'/prefix/*');
  798. $this->assertEquals($copyright_protection_ret->resource[1], $this->bucket.'/*/suffix');
  799. $this->client->deleteBucketCopyrightProtection($this->bucket);
  800. }
  801. public function testUserQuotaOperations(){
  802. $maxBucketCount=53;
  803. $maxCapacityMegaBytes=110;
  804. $this->client->putUserQuota($maxBucketCount,$maxCapacityMegaBytes,100);
  805. $this->assertEquals($this->client->getUserQuota()->maxBucketCount,$maxBucketCount);
  806. $this->assertEquals($this->client->getUserQuota()->maxCapacityMegaBytes,$maxCapacityMegaBytes);
  807. $this->client->deleteUserQuota();
  808. // $res = $this->client->getUserQuota();
  809. // $this->assertEquals($res->getErrorCode(),'UserQuotaNotConfigured');
  810. }
  811. public function testBucketObjectLock(){
  812. $BUCKET_NAME="bucketobjectest";
  813. $retentDays=20;
  814. $extendDays=30;
  815. $this->client->deleteBucket($BUCKET_NAME);
  816. $this->client->createBucket($BUCKET_NAME);
  817. $this->client->initBucketObjectLock($BUCKET_NAME, $retentDays);
  818. $this->assertEquals($this->client->getBucketObjectLock($BUCKET_NAME)->lockStatus, "IN_PROGRESS");
  819. $this->client->deleteBucketObjectLock($BUCKET_NAME);
  820. $this->client->initBucketObjectLock($BUCKET_NAME, $retentDays);
  821. $this->client->completeBucketObjectLock($BUCKET_NAME);
  822. $this->client->extendBucketObjectLock($BUCKET_NAME, $extendDays);
  823. $this->assertEquals($this->client->getBucketObjectLock($BUCKET_NAME)->retentionDays, $extendDays);
  824. }
  825. public function testBucketAndObject()
  826. {
  827. $diping_key = "diping_key";
  828. $diping_value = "diping_value";
  829. $this->client->putObjectFromString($this->bucket, $diping_key, $diping_value);
  830. $this->assertEquals(count($this->client->listObjects($this->bucket)->contents),1);
  831. $this->client->putBucketStorageClass($this->bucket,'STANDARD');
  832. $res = $this->client->getBucketStorageClass($this->bucket);
  833. $this->assertEquals($res->storageClass, "STANDARD");
  834. $deleteattay = array(
  835. array(
  836. "key"=>$diping_key
  837. ),
  838. );
  839. $this->client->deleteMultipleObjects($this->bucket, $deleteattay);
  840. $this->assertEquals(count($this->client->listObjects($this->bucket)->contents),0);
  841. }
  842. public function testRestoreObject() {
  843. $archiveDay = 10;
  844. $archiveKey = 'archiveKey';
  845. $archiveValue = 'archiveValue';
  846. $options = array(
  847. BosOptions::STORAGE_CLASS => StorageClass::ARCHIVE,
  848. );
  849. $this->client->putObjectFromString($this->bucket, $archiveKey, $archiveValue, $options);
  850. try {
  851. $this->client->restoreObject($this->bucket, $archiveKey, $archiveDay, "Stander");
  852. }
  853. catch(Exception $e) {
  854. echo $e->getMessage();
  855. }
  856. $this->client->restoreObject($this->bucket, $archiveKey);
  857. try {
  858. $this->client->restoreObject($this->bucket, $archiveKey, $archiveDay, "Expedited");
  859. }
  860. catch(Exception $e) {
  861. echo $e->getMessage();
  862. }
  863. try {
  864. $this->client->restoreObject($this->bucket, $archiveKey, $archiveDay, "Standard");
  865. }
  866. catch(Exception $e) {
  867. echo $e->getMessage();
  868. }
  869. $getObject = $this->client->getObjectMetadata($this->bucket, $archiveKey);
  870. }
  871. public function testNotification(){
  872. $mynotification =
  873. array(
  874. array(
  875. 'id'=> "water-test-1",
  876. 'name'=> "water-rule-1",
  877. 'appId'=> "water-app-id-1",
  878. 'status'=> "enabled",
  879. 'resources'=> array("/*.jpg", "/*.png"),
  880. 'events'=> array("PutObject") ,
  881. 'apps'=> array(
  882. array(
  883. 'id' => "app-id-1",
  884. 'eventUrl' => "https://op-log-app-service.chehejia.com/op-log-app-service/v1-0/log/bos/event",
  885. 'xVars' => "xvars",
  886. ),
  887. ),
  888. ));
  889. $this->client->putNotification($this->bucket,$mynotification);
  890. $getRes = $this->client->getNotification($this->bucket);
  891. $this->assertEquals($getRes->notifications[0]->appId,"water-app-id-1");
  892. $this->client->deleteNotification($this->bucket);
  893. }
  894. }