天天看点

java导出sas_[Azure Storage]使用Java上传文件到Storage并生成SAS签名

1 importjava.io.ByteArrayInputStream;2 importjava.io.File;3 importjava.io.FileInputStream;4 importjava.io.FileNotFoundException;5 importjava.io.IOException;6 importjava.net.URISyntaxException;7 importjava.security.InvalidKeyException;8 importjava.security.KeyManagementException;9 importjava.security.NoSuchAlgorithmException;10 importjava.security.SecureRandom;11 importjava.security.cert.X509Certificate;12 importjava.util.ArrayList;13 importjava.util.Calendar;14 importjava.util.Date;15 importjava.util.EnumSet;16 importjava.util.GregorianCalendar;17 importjava.util.Random;18 importjava.util.TimeZone;19

20 import javax.net.ssl.*;21

22 importcom.microsoft.azure.storage.CloudStorageAccount;23 importcom.microsoft.azure.storage.StorageCredentials;24 importcom.microsoft.azure.storage.StorageCredentialsAccountAndKey;25 importcom.microsoft.azure.storage.StorageException;26 importcom.microsoft.azure.storage.blob.BlobContainerPermissions;27 importcom.microsoft.azure.storage.blob.BlobContainerPublicAccessType;28 importcom.microsoft.azure.storage.blob.BlockEntry;29 importcom.microsoft.azure.storage.blob.BlockSearchMode;30 importcom.microsoft.azure.storage.blob.CloudBlobClient;31 importcom.microsoft.azure.storage.blob.CloudBlobContainer;32 importcom.microsoft.azure.storage.blob.CloudBlockBlob;33 importcom.microsoft.azure.storage.blob.SharedAccessBlobPermissions;34 importcom.microsoft.azure.storage.blob.SharedAccessBlobPolicy;35

36

37 public classJavaStorageClient {38

39 static final String storageAccountName = "";40 static final String storageAccountKey = "";41 static final String containerName = "";42 static final String videoPath = "<>";43 //static final String videoPath = "D:\\Training\\all hands meeting-1.mp4";

44

45 static CloudStorageAccount storageAccount = null;46

47 private static void Init() throwsInvalidKeyException, URISyntaxException, NoSuchAlgorithmException, KeyManagementException{48 TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){public X509Certificate[] getAcceptedIssuers(){return null;}49 public voidcheckClientTrusted(X509Certificate[] certs, String authType){}50 public voidcheckServerTrusted(X509Certificate[] certs, String authType){}}};51 SSLContext sc = SSLContext.getInstance("TLS");52 sc.init(null, trustAllCerts, newSecureRandom());53 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());54

55

56 StorageCredentials credentials = newStorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);57 String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.Chinacloudapi.cn", storageAccountName, storageAccountKey);58 storageAccount =CloudStorageAccount.parse(connectionString);59

60 }61

62 private static CloudBlobContainer GetContainer() throwsURISyntaxException, StorageException{63 CloudBlobClient blobClient =storageAccount.createCloudBlobClient();64 CloudBlobContainer container;65 container =blobClient.getContainerReference(containerName);66 container.createIfNotExists();67

68 returncontainer;69 }70

71 //For small size video, we can use this method.

72 private static void UploadSmallSize() throwsURISyntaxException, StorageException, FileNotFoundException, IOException, InvalidKeyException{73 System.out.println("===============Begin Uploading===============");74 File source = newFile(videoPath);75 String blobName =source.getName();76 CloudBlobContainer container =GetContainer();77 CloudBlockBlob blob =container.getBlockBlobReference(source .getName());78

79 blob.upload(newFileInputStream(source), source.length());80 System.out.println("===============Uploading Done===============");81 System.out.println("Blob URL: " +GetBlobUrl(container, blobName));82 }83

84

85 private static void UploadLargeSize() throwsURISyntaxException, StorageException, IOException, InvalidKeyException{86 File source = newFile(videoPath);87 String blobName =source.getName();88 FileInputStream inputStream = newFileInputStream(source);89 final int blockLength = 1 * 1024*1024;90 byte[] bufferBytes = new byte[blockLength];91 int blockCount = (int)(source.length() / blockLength) + 1;92 System.out.println("Total block count:"+blockCount+", Total size: "+source.length());93 int currentBlockSize = 0;94

95 CloudBlobContainer container =GetContainer();96 CloudBlockBlob blockBlobRef =container.getBlockBlobReference(blobName);97

98 System.out.println("===============Begin Uploading===============");99 ArrayList blockList = new ArrayList();100

101 for (int i = 0; i < blockCount; i++) {102 //String blockID="OWM3MDhiMWEtODdhNS00YjE5LWE2NmEtYzAzMGJmZWIyYzli";//String.format("%09d", i);103 //blockID=getBASE64(blockID);//Base64.encode(blockID.getBytes());104 //String blockID="b"+String.valueOf(id);105 //String blockID =Base64.encode(sid.getBytes());106 //String.format("%08d", String.valueOf(10000+i));//String.valueOf(1000000+i);//Base64.encode(String.valueOf(1000000+i).getBytes());

107 String blockID = String.format("%08d", i);108 currentBlockSize =blockLength;109 if (i == blockCount - 1){110 currentBlockSize = (int) (source.length() - blockLength *i);111 bufferBytes = new byte[currentBlockSize];112 }113

114 inputStream.read(bufferBytes, 0, currentBlockSize);115 blockBlobRef.uploadBlock(blockID, getRandomDataStream(blockLength), blockLength, null, null, null);116 blockList.add(newBlockEntry(blockID, BlockSearchMode.LATEST));117 System.out.println("Submitted block index:" + i + ", BlockIndex:" +blockID);118 }119 blockBlobRef.commitBlockList(blockList);120 System.out.println("===============Uploading Done===============");121

122

123 System.out.println("Blob URL: " +GetBlobUrl(container, blobName));124 }125

126 private static byte[] getRandomBuffer(intlength) {127 final Random randGenerator = newRandom();128 final byte[] buff = new byte[length];129 randGenerator.nextBytes(buff);130 returnbuff;131 }132

133

134 private static ByteArrayInputStream getRandomDataStream(intlength) {135 return newByteArrayInputStream(getRandomBuffer(length));136 }137

138 private static String GetBlobUrl(CloudBlobContainer container, String blobName) throwsStorageException, InvalidKeyException, URISyntaxException{139 SharedAccessBlobPolicy policy = newSharedAccessBlobPolicy();140 GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));141 calendar.setTime(newDate());142

143 //Immediately applicable

144 policy.setSharedAccessStartTime(calendar.getTime());145

146 //Applicable time span is 1 hour

147 calendar.add(Calendar.HOUR, 1);148 policy.setSharedAccessExpiryTime(calendar.getTime());149

150 //SAS grants READ access privileges

151 policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));152 BlobContainerPermissions containerPermissions = newBlobContainerPermissions();153

154 //Private blob-container with no access for anonymous users

155 containerPermissions.setPublicAccess(BlobContainerPublicAccessType.OFF);156 container.uploadPermissions(containerPermissions);157 String sas = container.generateSharedAccessSignature(policy,null);158

159 CloudBlockBlob blob =container.getBlockBlobReference(blobName);160 String blobUri =blob.getUri().toString();161

162 return blobUri + "?"+sas;163 }164

165 public static void main(String[] args) throwsFileNotFoundException, URISyntaxException, StorageException, IOException, InvalidKeyException, KeyManagementException, NoSuchAlgorithmException {166 //TODO Auto-generated method stub

167 Init();168 //UploadLargeSize();

169 UploadSmallSize();170 }171

172 }