@ -5,10 +5,15 @@ import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder ;
import com.amazonaws.services.s3.AmazonS3 ;
import com.amazonaws.services.s3.AmazonS3ClientBuilder ;
import com.amazonaws.services.s3.model.S3Object ;
import com.amazonaws.services.s3.model.S3ObjectInputStream ;
import com.fanruan.api.log.LogKit ;
import com.fr.io.base.provider.impl.ConfigRepositoryFactory ;
import com.fr.io.context.info.RepositoryProfile ;
import com.fr.io.repository.ResourceRepository ;
import com.fr.stable.AssistUtils ;
import java.io.IOException ;
/ * *
* @author richie
@ -18,6 +23,8 @@ import com.fr.io.repository.ResourceRepository;
public class S3RepositoryFactory extends ConfigRepositoryFactory < S3Config > {
static final String IDENTITY = "S3" ;
private static final String TEST_KEY = "test_key" ;
private static final String TEST_CONTENT = "test content" ;
public S3RepositoryFactory ( ) {
super ( IDENTITY ) ;
@ -40,16 +47,35 @@ public class S3RepositoryFactory extends ConfigRepositoryFactory<S3Config> {
AmazonS3 s3 = AmazonS3ClientBuilder . standard ( )
. withEndpointConfiguration ( new AwsClientBuilder . EndpointConfiguration ( config . getEndPoint ( ) , config . getRegion ( ) ) )
. withCredentials ( new AWSStaticCredentialsProvider ( credentials ) ) . build ( ) ;
s3 . listObjects ( config . getBucket ( ) ) ;
// listObjects方法存在问题,如果key中包含URL编码的内容,将会抛异常,修改为读写验证是否可用
s3 . putObject ( config . getBucket ( ) , TEST_KEY , TEST_CONTENT ) ;
try ( S3Object object = s3 . getObject ( config . getBucket ( ) , TEST_KEY ) ) {
final String content = getContent ( object ) ;
s3 . deleteObject ( config . getBucket ( ) , TEST_KEY ) ;
return AssistUtils . equals ( TEST_CONTENT , content ) ;
}
} catch ( Exception e ) {
LogKit . error ( e . getMessage ( ) , e ) ;
return false ;
}
return true ;
}
@Override
public ResourceRepository produce ( String repoName , String workRoot , S3Config config ) {
return new S3ResourceRepository ( repoName , workRoot , config ) ;
}
private String getContent ( S3Object object ) {
final StringBuilder stringBuilder = new StringBuilder ( ) ;
try ( S3ObjectInputStream objectContent = object . getObjectContent ( ) ) {
final byte [ ] bytes = new byte [ 4096 ] ;
int i = 0 ;
while ( ( i = objectContent . read ( bytes ) ) > - 1 ) {
stringBuilder . append ( new String ( bytes , 0 , i ) ) ;
}
} catch ( IOException e ) {
LogKit . error ( e . getMessage ( ) , e ) ;
}
return stringBuilder . toString ( ) ;
}
}