Skip to content

Commit a5d0290

Browse files
bgkleinxingwu1
authored andcommitted
Update java sample to 5.0.1 (#261)
1 parent 53dccd0 commit a5d0290

File tree

2 files changed

+73
-42
lines changed

2 files changed

+73
-42
lines changed

Java/PoolAndResourceFile/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
<dependency>
1818
<groupId>com.microsoft.azure</groupId>
1919
<artifactId>azure-batch</artifactId>
20-
<version>4.0.1</version>
20+
<version>5.0.1</version>
2121
</dependency>
2222
<dependency>
2323
<groupId>com.microsoft.rest</groupId>

Java/PoolAndResourceFile/src/main/java/PoolAndResourceFile.java

Lines changed: 72 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,27 @@
99
import com.microsoft.azure.storage.blob.*;
1010

1111
import com.microsoft.azure.batch.*;
12-
import com.microsoft.azure.batch.auth.BatchSharedKeyCredentials;
12+
import com.microsoft.azure.batch.auth.*;
1313
import com.microsoft.azure.batch.protocol.models.*;
1414

1515
public class PoolAndResourceFile {
1616

1717
/**
1818
* Create IaaS pool if pool isn't exist
19-
* @param client batch client instance
20-
* @param poolId the pool id
19+
*
20+
* @param client
21+
* batch client instance
22+
* @param poolId
23+
* the pool id
2124
* @return the pool instance
2225
* @throws BatchErrorException
2326
* @throws IllegalArgumentException
2427
* @throws IOException
2528
* @throws InterruptedException
2629
* @throws TimeoutException
2730
*/
28-
private static CloudPool createPoolIfNotExists(BatchClient client, String poolId) throws BatchErrorException, IllegalArgumentException, IOException, InterruptedException, TimeoutException {
31+
private static CloudPool createPoolIfNotExists(BatchClient client, String poolId)
32+
throws BatchErrorException, IllegalArgumentException, IOException, InterruptedException, TimeoutException {
2933
// Create a pool with 1 A1 VM
3034
String osPublisher = "OpenLogic";
3135
String osOffer = "CentOS";
@@ -37,7 +41,8 @@ private static CloudPool createPoolIfNotExists(BatchClient client, String poolId
3741
// Check if pool exists
3842
if (!client.poolOperations().existsPool(poolId)) {
3943

40-
// See detail of creating IaaS pool at https://blogs.technet.microsoft.com/windowshpc/2016/03/29/introducing-linux-support-on-azure-batch/
44+
// See detail of creating IaaS pool at
45+
// https://blogs.technet.microsoft.com/windowshpc/2016/03/29/introducing-linux-support-on-azure-batch/
4146
// Get the sku image reference
4247
List<NodeAgentSku> skus = client.accountOperations().listNodeAgentSkus();
4348
String skuId = null;
@@ -46,7 +51,8 @@ private static CloudPool createPoolIfNotExists(BatchClient client, String poolId
4651
for (NodeAgentSku sku : skus) {
4752
if (sku.osType() == OSType.LINUX) {
4853
for (ImageReference imgRef : sku.verifiedImageReferences()) {
49-
if (imgRef.publisher().equalsIgnoreCase(osPublisher) && imgRef.offer().equalsIgnoreCase(osOffer)) {
54+
if (imgRef.publisher().equalsIgnoreCase(osPublisher)
55+
&& imgRef.offer().equalsIgnoreCase(osOffer)) {
5056
imageRef = imgRef;
5157
skuId = sku.id();
5258
break;
@@ -82,15 +88,18 @@ private static CloudPool createPoolIfNotExists(BatchClient client, String poolId
8288
throw new TimeoutException("The pool did not reach a steady state in the allotted time");
8389
}
8490

85-
// The VMs in the pool don't need to be in and IDLE state in order to submit a job.
91+
// The VMs in the pool don't need to be in and IDLE state in order to submit a
92+
// job.
8693
// The following code is just an example of how to poll for the VM state
8794
startTime = System.currentTimeMillis();
8895
elapsedTime = 0L;
8996
boolean hasIdleVM = false;
9097

9198
// Wait for at least 1 VM to reach the IDLE state
9299
while (elapsedTime < VM_READY_TIMEOUT.toMillis()) {
93-
List<ComputeNode> nodeCollection = client.computeNodeOperations().listComputeNodes(poolId, new DetailLevel.Builder().withSelectClause("id, state").withFilterClause("state eq 'idle'").build());
100+
List<ComputeNode> nodeCollection = client.computeNodeOperations().listComputeNodes(poolId,
101+
new DetailLevel.Builder().withSelectClause("id, state").withFilterClause("state eq 'idle'")
102+
.build());
94103
if (!nodeCollection.isEmpty()) {
95104
hasIdleVM = true;
96105
break;
@@ -110,23 +119,28 @@ private static CloudPool createPoolIfNotExists(BatchClient client, String poolId
110119

111120
/**
112121
* Create blob container in order to upload file
113-
* @param storageAccountName storage account name
114-
* @param storageAccountKey storage account key
122+
*
123+
* @param storageAccountName
124+
* storage account name
125+
* @param storageAccountKey
126+
* storage account key
115127
* @return CloudBlobContainer instance
116128
* @throws URISyntaxException
117129
* @throws StorageException
118130
*/
119-
private static CloudBlobContainer createBlobContainer(String storageAccountName, String storageAccountKey) throws URISyntaxException, StorageException {
131+
private static CloudBlobContainer createBlobContainer(String storageAccountName, String storageAccountKey)
132+
throws URISyntaxException, StorageException {
120133
String CONTAINER_NAME = "poolsandresourcefiles";
121134

122135
// Create storage credential from name and key
123136
StorageCredentials credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);
124137

125-
// Create storage account. The 'true' sets the client to use HTTPS for communication with the account
138+
// Create storage account. The 'true' sets the client to use HTTPS for
139+
// communication with the account
126140
CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, true);
127141

128142
// Create the blob client
129-
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
143+
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
130144

131145
// Get a reference to a container.
132146
// The container name must be lower case
@@ -135,16 +149,21 @@ private static CloudBlobContainer createBlobContainer(String storageAccountName,
135149

136150
/**
137151
* Upload file to blob container and return sas key
138-
* @param container blob container
139-
* @param fileName the file name of blob
140-
* @param filePath the local file path
152+
*
153+
* @param container
154+
* blob container
155+
* @param fileName
156+
* the file name of blob
157+
* @param filePath
158+
* the local file path
141159
* @return SAS key for the uploaded file
142160
* @throws URISyntaxException
143161
* @throws IOException
144162
* @throws InvalidKeyException
145163
* @throws StorageException
146164
*/
147-
private static String uploadFileToCloud(CloudBlobContainer container, String fileName, String filePath) throws URISyntaxException, IOException, InvalidKeyException, StorageException {
165+
private static String uploadFileToCloud(CloudBlobContainer container, String fileName, String filePath)
166+
throws URISyntaxException, IOException, InvalidKeyException, StorageException {
148167
// Create the container if it does not exist.
149168
container.createIfNotExists();
150169

@@ -170,17 +189,24 @@ private static String uploadFileToCloud(CloudBlobContainer container, String fil
170189

171190
/**
172191
* Create a job with a single task
173-
* @param client batch client instance
174-
* @param container blob container to upload the resource file
175-
* @param poolId pool id
176-
* @param jobId job id
192+
*
193+
* @param client
194+
* batch client instance
195+
* @param container
196+
* blob container to upload the resource file
197+
* @param poolId
198+
* pool id
199+
* @param jobId
200+
* job id
177201
* @throws BatchErrorException
178202
* @throws IOException
179203
* @throws StorageException
180204
* @throws InvalidKeyException
181205
* @throws URISyntaxException
182206
*/
183-
private static void submitJobAndAddTask(BatchClient client, CloudBlobContainer container, String poolId, String jobId) throws BatchErrorException, IOException, StorageException, InvalidKeyException, URISyntaxException {
207+
private static void submitJobAndAddTask(BatchClient client, CloudBlobContainer container, String poolId,
208+
String jobId)
209+
throws BatchErrorException, IOException, StorageException, InvalidKeyException, URISyntaxException {
184210
String BLOB_FILE_NAME = "test.txt";
185211
String LOCAL_FILE_PATH = "./" + BLOB_FILE_NAME;
186212

@@ -197,7 +223,7 @@ private static void submitJobAndAddTask(BatchClient client, CloudBlobContainer c
197223

198224
// Associate resource file with task
199225
ResourceFile file = new ResourceFile();
200-
file.withFilePath(BLOB_FILE_NAME).withBlobSource(sas);
226+
file.withFilePath(BLOB_FILE_NAME).withHttpUrl(sas);
201227
List<ResourceFile> files = new ArrayList<ResourceFile>();
202228
files.add(file);
203229
taskToAdd.withResourceFiles(files);
@@ -208,20 +234,26 @@ private static void submitJobAndAddTask(BatchClient client, CloudBlobContainer c
208234

209235
/**
210236
* Wait all tasks under a specified job to be completed
211-
* @param client batch client instance
212-
* @param jobId job id
213-
* @param expiryTime the waiting period
237+
*
238+
* @param client
239+
* batch client instance
240+
* @param jobId
241+
* job id
242+
* @param expiryTime
243+
* the waiting period
214244
* @return if task completed in time, return true, otherwise, return false
215245
* @throws BatchErrorException
216246
* @throws IOException
217247
* @throws InterruptedException
218248
*/
219-
private static boolean waitForTasksToComplete(BatchClient client, String jobId, Duration expiryTime) throws BatchErrorException, IOException, InterruptedException {
249+
private static boolean waitForTasksToComplete(BatchClient client, String jobId, Duration expiryTime)
250+
throws BatchErrorException, IOException, InterruptedException {
220251
long startTime = System.currentTimeMillis();
221252
long elapsedTime = 0L;
222253

223254
while (elapsedTime < expiryTime.toMillis()) {
224-
List<CloudTask> taskCollection = client.taskOperations().listTasks(jobId, new DetailLevel.Builder().withSelectClause("id, state").build());
255+
List<CloudTask> taskCollection = client.taskOperations().listTasks(jobId,
256+
new DetailLevel.Builder().withSelectClause("id, state").build());
225257

226258
boolean allComplete = true;
227259
for (CloudTask task : taskCollection) {
@@ -249,12 +281,15 @@ private static boolean waitForTasksToComplete(BatchClient client, String jobId,
249281

250282
/**
251283
* print BatchErrorException to console
252-
* @param err BatchErrorException instance
284+
*
285+
* @param err
286+
* BatchErrorException instance
253287
*/
254288
private static void printBatchException(BatchErrorException err) {
255289
System.out.println(String.format("BatchError %s", err.toString()));
256290
if (err.body() != null) {
257-
System.out.println(String.format("BatchError code = %s, message = %s", err.body().code(), err.body().message().value()));
291+
System.out.println(String.format("BatchError code = %s, message = %s", err.body().code(),
292+
err.body().message().value()));
258293
if (err.body().values() != null) {
259294
for (BatchErrorDetail detail : err.body().values()) {
260295
System.out.println(String.format("Detail %s=%s", detail.key(), detail.value()));
@@ -288,10 +323,10 @@ public static void main(String argv[]) throws Exception {
288323

289324
String userName = System.getProperty("user.name");
290325
String poolId = userName + "-pooltest";
291-
String jobId = "HelloWorldJob-" + userName + "-" + (new Date()).toString().replace(' ', '-').replace(':', '-').replace('.', '-');
326+
String jobId = "HelloWorldJob-" + userName + "-"
327+
+ (new Date()).toString().replace(' ', '-').replace(':', '-').replace('.', '-');
292328

293-
try
294-
{
329+
try {
295330
CloudPool sharedPool = createPoolIfNotExists(client, poolId);
296331
submitJobAndAddTask(client, container, sharedPool.id(), jobId);
297332
if (waitForTasksToComplete(client, jobId, TASK_COMPLETE_TIMEOUT)) {
@@ -302,18 +337,14 @@ public static void main(String argv[]) throws Exception {
302337
client.fileOperations().getFileFromTask(jobId, task.id(), STANDARD_CONSOLE_OUTPUT_FILENAME, stream);
303338
String fileContent = stream.toString("UTF-8");
304339
System.out.println(fileContent);
305-
}
306-
else {
340+
} else {
307341
throw new TimeoutException("Task did not complete within the specified timeout");
308342
}
309-
}
310-
catch (BatchErrorException err) {
343+
} catch (BatchErrorException err) {
311344
printBatchException(err);
312-
}
313-
catch (Exception ex) {
345+
} catch (Exception ex) {
314346
ex.printStackTrace();
315-
}
316-
finally {
347+
} finally {
317348
// Clean up the resource if necessary
318349
if (shouldDeleteJob) {
319350
try {

0 commit comments

Comments
 (0)