-
Notifications
You must be signed in to change notification settings - Fork 34
/
Quickstart.java
226 lines (193 loc) · 9.97 KB
/
Quickstart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package quickstart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.StandardOpenOption;
import java.security.InvalidKeyException;
import com.microsoft.azure.storage.blob.BlockBlobURL;
import com.microsoft.azure.storage.blob.ContainerURL;
import com.microsoft.azure.storage.blob.ListBlobsOptions;
import com.microsoft.azure.storage.blob.PipelineOptions;
import com.microsoft.azure.storage.blob.ServiceURL;
import com.microsoft.azure.storage.blob.SharedKeyCredentials;
import com.microsoft.azure.storage.blob.StorageURL;
import com.microsoft.azure.storage.blob.TransferManager;
import com.microsoft.azure.storage.blob.models.BlobItem;
import com.microsoft.azure.storage.blob.models.ContainerCreateResponse;
import com.microsoft.azure.storage.blob.models.ContainerListBlobFlatSegmentResponse;
import com.microsoft.rest.v2.RestException;
import io.reactivex.*;
/*
* This file uses an outdated library. Please see the readme to find the latest version.
*/
public class Quickstart {
//Deprecated Libraries
static File createTempFile() throws IOException {
// Here we are creating a temporary file to use for download and upload to Blob storage
File sampleFile = null;
sampleFile = File.createTempFile("sampleFile", ".txt");
System.out.println(">> Creating a sample file at: " + sampleFile.toString());
Writer output = new BufferedWriter(new FileWriter(sampleFile));
output.write("Hello Azure.");
output.close();
return sampleFile;
}
//Deprecated Libraries
static void uploadFile(BlockBlobURL blob, File sourceFile) throws IOException {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sourceFile.toPath());
// Uploading a file to the blobURL using the high-level methods available in TransferManager class
// Alternatively call the PutBlob/PutBlock low-level methods from BlockBlobURL type
TransferManager.uploadFileToBlockBlob(fileChannel, blob, 8*1024*1024, null, null)
.subscribe(response-> {
System.out.println("Completed upload request.");
System.out.println(response.response().statusCode());
});
}
//Deprecated Libraries
static void listBlobs(ContainerURL containerURL) {
// Each ContainerURL.listBlobsFlatSegment call return up to maxResults (maxResults=10 passed into ListBlobOptions below).
// To list all Blobs, we are creating a helper static method called listAllBlobs,
// and calling it after the initial listBlobsFlatSegment call
ListBlobsOptions options = new ListBlobsOptions();
options.withMaxResults(10);
containerURL.listBlobsFlatSegment(null, options, null).flatMap(containerListBlobFlatSegmentResponse ->
listAllBlobs(containerURL, containerListBlobFlatSegmentResponse))
.subscribe(response-> {
System.out.println("Completed list blobs request.");
System.out.println(response.statusCode());
});
}
//Deprecated Libraries
private static Single <ContainerListBlobFlatSegmentResponse> listAllBlobs(ContainerURL url, ContainerListBlobFlatSegmentResponse response) {
// Process the blobs returned in this result segment (if the segment is empty, blobs() will be null.
if (response.body().segment() != null) {
for (BlobItem b : response.body().segment().blobItems()) {
String output = "Blob name: " + b.name();
if (b.snapshot() != null) {
output += ", Snapshot: " + b.snapshot();
}
System.out.println(output);
}
}
else {
System.out.println("There are no more blobs to list off.");
}
// If there is not another segment, return this response as the final response.
if (response.body().nextMarker() == null) {
return Single.just(response);
} else {
/*
IMPORTANT: ListBlobsFlatSegment returns the start of the next segment; you MUST use this to get the next
segment (after processing the current result segment
*/
String nextMarker = response.body().nextMarker();
/*
The presence of the marker indicates that there are more blobs to list, so we make another call to
listBlobsFlatSegment and pass the result through this helper function.
*/
return url.listBlobsFlatSegment(nextMarker, new ListBlobsOptions().withMaxResults(10), null)
.flatMap(containersListBlobFlatSegmentResponse ->
listAllBlobs(url, containersListBlobFlatSegmentResponse));
}
}
//Deprecated Libraries
static void deleteBlob(BlockBlobURL blobURL) {
// Delete the blob
blobURL.delete(null, null, null)
.subscribe(
response -> System.out.println(">> Blob deleted: " + blobURL),
error -> System.out.println(">> An error encountered during deleteBlob: " + error.getMessage()));
}
//Deprecated Libraries
static void getBlob(BlockBlobURL blobURL, File sourceFile) throws IOException {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sourceFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
TransferManager.downloadBlobToFile(fileChannel, blobURL, null, null)
.subscribe(response-> {
System.out.println("Completed download request.");
System.out.println("The blob was downloaded to " + sourceFile.getAbsolutePath());
});
}
//Deprecated Libraries
public static void main(String[] args) throws java.lang.Exception{
ContainerURL containerURL;
// Creating a sample file to use in the sample
File sampleFile = null;
try {
sampleFile = createTempFile();
File downloadedFile = File.createTempFile("downloadedFile", ".txt");
// Retrieve the credentials and initialize SharedKeyCredentials
String accountName = System.getenv("AZURE_STORAGE_ACCOUNT");
String accountKey = System.getenv("AZURE_STORAGE_ACCESS_KEY");
// Create a ServiceURL to call the Blob service. We will also use this to construct the ContainerURL
SharedKeyCredentials creds = new SharedKeyCredentials(accountName, accountKey);
// We are using a default pipeline here, you can learn more about it at https://github.com/Azure/azure-storage-java/wiki/Azure-Storage-Java-V10-Overview
final ServiceURL serviceURL = new ServiceURL(new URL("https://" + accountName + ".blob.core.windows.net"), StorageURL.createPipeline(creds, new PipelineOptions()));
// Let's create a container using a blocking call to Azure Storage
// If container exists, we'll catch and continue
containerURL = serviceURL.createContainerURL("quickstart");
try {
ContainerCreateResponse response = containerURL.create(null, null, null).blockingGet();
System.out.println("Container Create Response was " + response.statusCode());
} catch (RestException e){
if (e instanceof RestException && ((RestException)e).response().statusCode() != 409) {
throw e;
} else {
System.out.println("quickstart container already exists, resuming...");
}
}
// Create a BlockBlobURL to run operations on Blobs
final BlockBlobURL blobURL = containerURL.createBlockBlobURL("SampleBlob.txt");
// Listening for commands from the console
System.out.println("Enter a command");
System.out.println("(P)utBlob | (L)istBlobs | (G)etBlob | (D)eleteBlobs | (E)xitSample");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("# Enter a command : ");
String input = reader.readLine();
switch(input){
case "P":
System.out.println("Uploading the sample file into the container: " + containerURL );
uploadFile(blobURL, sampleFile);
break;
case "L":
System.out.println("Listing blobs in the container: " + containerURL );
listBlobs(containerURL);
break;
case "G":
System.out.println("Get the blob: " + blobURL.toString() );
getBlob(blobURL, downloadedFile);
break;
case "D":
System.out.println("Delete the blob: " + blobURL.toString() );
deleteBlob(blobURL);
System.out.println();
break;
case "E":
System.out.println("Cleaning up the sample and exiting.");
containerURL.delete(null, null).blockingGet();
downloadedFile.delete();
System.exit(0);
break;
default:
break;
}
}
} catch (InvalidKeyException e) {
System.out.println("Invalid Storage account name/key provided");
} catch (MalformedURLException e) {
System.out.println("Invalid URI provided");
} catch (RestException e){
System.out.println("Service error returned: " + e.response().statusCode() );
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}